Java/[국비] JAVA

[국비][JAVA] this 이해하기

줌인. 2024. 5. 30. 23:48
this는 자기 자신을 부르는 이름표와 같음
객체 생성 후 메서드 호출 시, 메서드 내에서 this는 호출된 객체를 가리킴


this 키워드
- this 키워드는 현재 객체를 참조하는 역할
- 클래스 내에서 this를 사용하여 객체의 필드와 메서드를 참조
- 객체 생성 후 메서드를 호출하면, 해당 메서드 내에서 this는 호출된 객체를 가리

this 키워드는 마치 자기 자신을 부르는 이름표와 같음

ex) momCar.info()를 호출하면, info 메서드 안에서 this는 momCar를 가리킴

      > 이는 info 메서드가 momCar의 속성과 메서드를 사용할 수 있게 합니다.

[예시코드]

public class Ex3Main {
    public static void main(String[] args) {
        Car momCar = new Car();
        momCar.color = "white";
        momCar.brand = "모닝";
        momCar.company = "기아";
        momCar.info(); // x001

        Car fatherCar = new Car();
        fatherCar.color = "white";
        fatherCar.brand = "소나타";
        fatherCar.company = "현대";
        fatherCar.info(); // x002
    }
}

class Car {
    String color;
    String brand;
    String company;

    // this: 현재 객체를 참조. 객체 생성 시, 해당 객체의 주소를 담음
    public void info() {
        // 현재 객체(this)의 정보를 출력
        System.out.println(this); // 현재 객체의 참조값 출력
        System.out.println(this.color); // 현재 객체의 color 필드 값 출력
        System.out.println(this.brand); // 현재 객체의 brand 필드 값 출력
        this.go(); // 현재 객체의 go() 메서드 호출
    }

    public void go() {
        System.out.println(this.company); // 현재 객체의 company 필드 값 출력
    }
}

※ Car car을 선언하지 않아도 됨

※ Class type 즉 이것(this)를 가리킨다고 이해하자

 

[도식화]

 

728x90