190223 생성자
생성자에서 다른 생성자를 호출할때,
1. 생성자의 이름으로 클래스이름 대신 this를 사용한다.
2. 한 생성자에서 다른 생성자를 호출할 때는 반드시 첫줄에서만 호출이 가능하다.
public class ex {
public static void main(String[] args) {
Car c1=new Car();
System.out.println(c1.color+c1.gearType+c1.door);
Car c2=new Car("red");
System.out.println(c2.color+c2.gearType+c2.door);
}
}
class Car{
String color; //색상
String gearType; //변속기종류
int door; //문의개수
Car(){ //Car(String color, String gearType, int door)를 호출
this("white","auto",4);
}; //기본생성자
Car(String color){
this.color=color;
}
Car(String color, String gearType, int door){
this.color=color;
this.gearType=gearType;
this.door=door;
}
}
this 인스턴스 자신을 가리키는 참조변수, 인스턴스의 주소가 저장되어있다.
this(),this(매개변수) 생성자, 같은 클래스의 다른 생성자를 호출할 때 사용한다.
생성자를 이용한 인스턴스의 복사
클래스의 참조변수를 매개변수로 선언하여 복사한다.
public class ex {
public static void main(String[] args) {
Car c1=new Car();
Car c2=new Car(c1); //c1의 복사본 c2를 생성한다.
System.out.println(c1.color+c1.gearType+c1.door);
System.out.println(c2.color+c2.gearType+c2.door);
c1.door=100;
//c1의 인스턴스 변수 door 변경 후
System.out.println(c1.color+c1.gearType+c1.door);
System.out.println(c2.color+c2.gearType+c2.door);
}
}
class Car{
String color; //색상
String gearType; //변속기종류
int door;
Car(){
this("white","auto",4);
}
Car(Car c){
this(c.color, c.gearType, c.door);
// color=c.color;
// gearType=c.gearType;
// door=c.door;
}
Car(String color, String gearType, int door){
this.color=color;
this.gearType=gearType;
this.door=door;
}
}
Class Car{
int door=4; //기본형 변수의 초기화
Engine e=new Engine(); //참조형 변수의 초기화
//...
2.초기화블럭
-클래스 초기화 블럭: 클래스변수의 복잡한 초기화에 사용된다. static{...{
-인스턴스 초기화 블럭: 인스턴스변수의 복잡한 초기화에 사용된다. {...}
클래스변수는 클래스가 메모리에 처음 로딩될 때 한번만 수행되며, 인스턴스 초기화 블럭은 생성자와 같이 인스턴스를 생성할 때 마다 수행된다.
public class ex { public static void main(String[] args) { System.out.println("BlockTest bt=new BlockTest();"); BlockTest bt=new BlockTest(); System.out.println("BlockTest bt2=new BlockTest();"); BlockTest bt2=new BlockTest(); } } class BlockTest{ static { System.out.println("static{ }"); //클래스 초기화 블럭 } { System.out.println("{ }"); //인스턴스 초기화 블럭 } BlockTest(){ System.out.println("생성자"); } }