형식)
클래스이름 참조변수 = new 클래스이름( ); ==> X
클래스이름 참조변수 = new 생성자( );
[접근제한] 생성자이름(매개변수) {
생성자 호출 시 실행될 문장;
}
학생의 학번, 이름, 학과, 연락처, 주소 멤버변수를 만들고 기본 생성자와 인자 생성자를 만들어보자
============================코드============================
public class Student {
// 멤버변수
int hakbun; // 학생 학번
String name; // 학생 이름
String major; // 학생 학과
String phone; // 학생 연락처
String addr; // 학생 주소
public Student() { // 기본 생성자 : 안에 매개변수가 없음 (ctrl + space바 누르면 나옴)
}
public Student(int h, String n, String m, String p, String a) { // 인자 생성자
hakbun = h;
name = n;
major = m;
phone = p;
addr = a;
} // 인자 생성자 end
// 멤버메서드
void getStudentInfo() {
System.out.println("학생 학번 >>> " + hakbun);
System.out.println("학생 이름 >>> " + name);
System.out.println("학생 학과 >>> " + major);
System.out.println("학생 연락처 >>> " + phone);
System.out.println("학생 주소 >>> " + addr);
} // getStudentInfo() 메서드 end
}
기본 생성자, 인자 생성자로 객체를 생성할 Student_04 클래스, 키보드로 입력을 받아 객체를 생성할 Student_05를 만들자!

기본 생성자로 객체를 생성하고 아래와 같이 화면에 출력해보자
학생 학번 >>> 2024001
학생 이름 >>> 홍길동
학생 학과 >>> 경제학과
학생 연락처 >>> 010-1111-1234
학생 주소 >>> 서울시 구로구
============================코드============================
// 기본 생성자로 객체를 생성하는 방법
Student student = new Student();
student.hakbun = 2024001;
student.name = "홍길동";
student.major = "경제학과";
student.phone = "010-1111-1234";
student.addr = "서울시 구로구";
student.getStudentInfo();

인자 생성자로 객체를 생성하고 아래와 같이 화면에 출력해보자
학생 학번 >>> 2024002
학생 이름 >>> 세종대왕
학생 학과 >>> 국문학과
학생 연락처 >>> 010-2222-2345
학생 주소 >>> 서울시 중구
============================코드============================
// 인자 생성자로 객체를 생성하는 방법
Student student2 = new Student(2024002, "세종대왕", "국문학과", "010-2222-2345", "서울시 중구");
// int h, String n, String m, String p, String a ==> 멤버변수로 값이 넘어감
student2.getStudentInfo();

키보드로 입력을 받아 화면에 출력하는 객체를 만들어보자!
============================코드============================
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("학생의 학번, 이름, 학과, 연락처, 주소를 입력하세요.");
Student student = new Student(sc.nextInt(), sc.next(), sc.next(), sc.next(), sc.next());
student.getStudentInfo();
sc.close();
}
