☕ 자바 JAVA/☕ 클래스와 함수 Class & Method

[JAVA]생성자 this()와 참조변수 this

yeun.log 2024. 3. 10. 05:15
반응형
똑같이 생겼지만 ()가 붙느냐의 차이로
전혀 다른 역할을 합니다

 


 

생성자 this ()
: 같은 class의 다른 생성자를 호출 시 사용

 

class Car2 {
    String color;
    String gearType;
    int door;

    Car2() {
        /*
        코드의 중복을 제거
        color = "white";
        gearType = "quto";
        door = 4;
        이렇게 쓰는 대신 this를 사용해 아래처럼 쓸 수 있다.
        */
        this("white", "auto", 4);
    }
    
    Car2(String color) {
        /*
         * 다른 생성자 호출 시 첫 줄에서만 사용해야 한다.
         * color = "white"; -> X
         * 
         * 같은 클래스 안의 생성자 호출시 class이름 대신 this를 사용해야 한다.
         * Car2(color, "auto", 2);
        */
        this(color, "auto", 4);
    }

    Car2(String color, String gearType, int door) {
        this.color = color;
        this.gearType = gearType;
        this.door = door;
    }
}
  • 호출 시 첫줄에서만 사용해야 한다.
  • 같은 클래스 안의 생성자 호출 시 class이름 대신 this를 사용해야 한다.

 


 

참조변수 this
:인스턴스 자신을 가리키는 참조변수
인스턴스의 주소가 저장되어 있다

 

class car {
    String color;   // this.color
    String gearType;// this.gearType
    int door;       // this.door
    
    car(){}
    car(String color, String gearType, int door){
        /**
         * parameter lv와 변수명이 같은 경우
         * this가 붙은 변수는 iv로 이용할 수 있다.
         */
        this.color = color;
        this.gearType = gearType;
        this.door = door;
    }
    
    // * this는 iv이기 때문에 static 메서드에서는 사용불가.
    static long add(long a, long b) {
        // return this.door = 3;
        return 0;
    }
}
  • 인스턴스 메서드에서만 사용가능.
  • 지역변수lv와 구별할 때 사용.
  • static method에서는 사용 불가.
  • parameter 지역변수lv와 변수명이 같은 경우, this가 붙은 변수는 인스턴스변수iv로 이용할 수 있다.

 

 

반응형

'☕ 자바 JAVA > ☕ 클래스와 함수 Class & Method' 카테고리의 다른 글

[JAVA]포함 composite  (1) 2024.03.22
[JAVA]상속 Inheritance  (1) 2024.03.13
[JAVA]생성자 Constructor  (1) 2023.10.03
[JAVA]오버로딩 Overloading  (0) 2023.10.03
[JAVA]Method의 Return문이란  (0) 2023.09.17