📚 참고
자바의 정석 기초편 (객체지향개념만)

 

 

 

 

 

 

 

 

 

생성자 this()

 

  • 같은 클래스다른 생성자를 호출할 때 사용 (클래스명 대신 this() 사용)
  • 다른 생성자 호출 시, 첫 줄에서만 사용 가능
  • 생성자 this를 통해 코드의 중복을 제거할 수 있다.

 

class Car2 {
    String color;
    String gearType;
    int door;
    
    // 4번째 생성자를 호출
    Car2() {
    	this("white", "auto", 4);
    }
    
    // 4번째 생성자를 호출
    Car2(String color) {
    	this(color, "auto", 4);
    }
    
    // 🚩에러
    // 1. 첫 줄에 생성자를 호출해야함
    // 2. 같은 클래스 안의 다른 생성자를 호출할 땐, 클래스명이 아닌 this 사용
    Car2(String color) {
    	door = 5;
        Car2(color, "auto", 4);
    }

    Car2(String color, String gearType, int door) {
    	this.color = color;
        this.gearType = gearType;
        this.door = door;
    }
}

 

 

 

 

 

 

 

참조변수 this

 

  • 인스턴스 자신을 가리키는 참조변수 (인스턴스의 주소가 저장)
  • 생성자, 인스턴스 메서드에서 사용 가능 (static 메서드에서는 사용불가)
  • 인스턴스 메서드의 지역변수로 숨겨진 채 존재함
  • 지역변수(lv)와 인스턴스 변수(iv)를 구별할 때 사용

 

Car(String c, String g, int d) {
    // 같은 클래스 내에서 참조변수 this는 생략 가능 (원래는 this.color)
    // color = iv, c = lv
    
    color = c;
    gearType = g;
    door =d;
}

Car(String color, String gearType, int door) {
    // this.color = iv, color = lv
    // this가 있어야 iv로 간주된다.
    // this가 없으면 lv로 간주된다. 왜냐하면 같은 이름의 지역변수(매개변수)가 있으니까

    this.color = color;
    this.gearType = gearType;
    this.door =door;
}

 

 

 

 

 

 

 

참조변수 this와 생성자 this()

 

  • this와 this()는 비슷하게 생겼을 뿐 완전히 다름 (this는 참조변수, this()는 생성자)

 

class MyMath2 {
    // this.a, this.b (iv의 진짜 이름)
    long a, b;
    
    // 생성자
    MyMath2(int a, int b) {
    	// this 생략불가
    	this.a = a;
        this.b = b;
    }
    
    // 인스턴스 메서드
    // this는 인스턴스 메서드에 지역변수로 숨겨진 채 존재함
    long add() {
    	return a + b;	// return this.a + this.b (this 생략가능)
    }
    
    // 클래스 메서드 (static 메서드)
    // iv 사용불가 ➡ this(객체 자신) 사용불가
    static long add(long a, long b) {
    	return a + b;
    }
}

 

 

 

 

 

 

 

 

 

 

'JAVA > 객체지향개념' 카테고리의 다른 글

상속 (Inheritance)  (0) 2021.03.15
변수 초기화  (0) 2021.03.13
생성자 (Constructor)  (0) 2021.03.11
오버로딩 (Overloading)  (0) 2021.03.11
Instance 메서드 vs Static 메서드  (0) 2021.03.11