- 하나의 class에는 반드시 하나 이상의 생성자가 존재해야 한다.
- 생성자는 객체가 생성될때, new 연산자를 사용하여 호출된다
- (붕어빵을 만들려면 붕어빵 틀을 먼저 만들어야 한다.)
- 생성자는 인스턴스를 생성할 때 멤버 변수를 초기화 하는 코드가 주를 이루고 있다.
- 생성자는 반드시 class와 이름이 같아야 한다.
- 생성자는 일반 메서드와는 다르게 return 값이 없고, 상속이 되지 않는다
생성자 생성 : public 클래스명(){}
class Constructor {
int x;
int y;
String z;
public Constructor() {
this(1, 2, "");
}
public Constructor(int i, int j, String string) {
this.x=i;
this.y=j;
this.z=string;
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Constructor c = new Constructor();
System.out.println(c.x+","+c.y+","+c.z);
}
}
여러 입력 인자를 입력받는 메소드로 기본 생성자를 오버로딩하여 만든 메서드 이다.
생성자를 여러개 오버로딩 할 때는 this 키워드를 사용하여 이미 만들어둔 생성자를 참조하여서 코드 중복사용을 줄인다.
Object를 초기화하는 역할이다.
생성자에서는 값을 초기화 해주는것만 ! 초기화 안해준 다른 멤버변수들은 0 이나 null값(참조변수)!
class Student{
public int studentID;
public String studentName;
public String address;
// 생성자 1
public Student(String name) {
studentName = name;
}
// 생성자 2
public Student(int id, String name) {
studentID = id;
studentName = name;
address = "주소 없음 ";
}
public void showStudentInfo() {
System.out.println(studentName + "," + address );
}
public String getStudentName() {
return studentName;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("이매정 "); // 생성자 1 사용
s1.address = "서울 ";
s1.showStudentInfo(); //이매정, 서울
Student s2 = new Student(1234, "서혜원 "); // 생성자 2 사용
s2.showStudentInfo(); // 서혜원, 주소 없음
}
}
객체 변수를 정의하는것과 객체를 생성하는것은 별개다.
ex) Circle myCircle = new Circle(2.0)
객체를 생성하는것이다(new 사용)
2.0이라는 지정된 반지름을 갖는 Circle Object를 생성한다
해당 객체의 변수에 대한 공간 확보, 메소드 실행 준비를 한다
stack에 할당 할 수 없고, heap에 준비를 한다