this : 인스턴스 자신을 가리키는 참조변수, 인스턴스의 주소가 저장되어있다.
모든 인스턴스 메서드에 지역변수로 숨겨진 채로 존재한다
--> 인스턴스 변수에 접근할 수있음
this(),this(매개변수) 생성자 같은 클래스의 다른생성자를 호출할 떄 사용한다.
package Algorithm;
//클래스 이름명 주의하기 Car 가 있을 경우 car는 안된다
class car1{
String color;
String gearType;
int door;
// this(),this(매개변수) 생성자, 같은 클래스의 다른 생성자를 호출할 떄 사용한다.
car1(){
this("white","auto",4);
}
//참조변수를 매개변수로 선언한 생성자
// 참조 변수를 통해 인스턴스의 멤버에 접근할 수 있는것 처럼 this로 인스턴스변수에 접근할 수 있는것이다.
// car1(car1 c){
// color = c.color;
// gearType = c.gearType;
// door = c.door;
//
// }
//
// 참조변수를 매개변수로 선언한 생성자 2 더 간결하게 바꿔준다.
car1(car1 c){
this(c.color,c.gearType,c.door);
}
//this --> 인스턴스 자신을 가리키는 참조변수, 인스턴스의 주소가 저장되어 있다.
// 모든 인스턴스메서드에 지역변수로 숨겨진 채로 존재한다.
car1(String color, String gearType,int door){
this.color = color;
this.gearType=gearType;
this.door=door;
}
}
public class constructor_test_02 {
public static void main(String[] args) {
car1 c1= new car1();
car1 c2 = new car1(c1); //c1 객체 복사
System.out.println("c1 =>"+c1.color); //white
System.out.println("c2=>"+c2.color); //white c1복사
c1.color="black";
System.out.println("c1 after =>"+c1.color); //balck
System.out.println("c2 after =>"+c2.color); //white 복사된 객체이지만 값은 변경이 안된다
}
}