Study/Java
[Java] 생성자
별천랑
2021. 5. 6. 17:51
기본 생성자
class ExamList {
private Exam[] exams;
private int current;
public ExamList() {
exams = new Exam[3];
current = 0;
}
}
기본 생성자 제거
- 기본 생성자가 없다면, 기본 생성자는 사용할 수 없다.
class ExamList {
private Exam[] exams;
private int current;
public ExamList(int size) {
exams = new Exam[size];
current = 0;
}
}
생성자 오버 로딩
- 생성자 오버 로딩 함수의 중복을 제거해서 구현한다.
- 항상 먼저 생성자 호출 후 새로운 값을 초기화해야 한다.
class ExamList {
private Exam[] exams;
private int current;
public ExamList() {
this(3);
}
public ExamList(int size) {
exams = new Exam[size];
current = 0;
}
}
생성자 정의하지 않을 때
- 생성자가 하나도 없다면, 컴파일러가 컴파일할 때 기본 생성자가 생성됨
- 참조 변수는 null. 기본 타입은 0으로 세팅함 > 다른 값 세팅은 생성자 구현
상속받을 때 생성자
class Exam {
private int kor;
private int math;
public Exam() {
this(0, 0);
}
public Exam(int kor, int math) {
this.kor = kor;
this.math = math;
}
}
class NewExam extends Exam {
private int eng;
public NewExam() {
/*
super(0,0);
this.eng = 0;
*/
this(0, 0, 0);
}
public NewExam(int kor, int math, int eng) {
super(kor, math); // 항상 먼저 생성자 호출 후,
this.eng = eng; // 새로운 값을 초기화해야 한다.
}
}