본문 바로가기
내가 보려고 정리한 JAVA

[자바 객체 문법] this 키워드

by nacastle 2020. 4. 18.

"자바에서 this 는 '나 자신의 객체' 를 나타낸다."

 

 

this가 사용되는 경우(사용될 수밖에 없는 경우)는 주로 3가지가 있다.

 

1. 클래스의 필드(=멤버변수, 전역변수)와 생성자/메소드의  파라미터(=매개변수)의 이름이 같을 경우

 

코드로 알아보는 것이 더 이해하기 쉽다...


public class Car {

    String model;
    String color;
    int maxSpeed;

    Car(String model, String color, int maxSpeed) {


       // 좌변은 필드값, 우변은 파라미터값
       this.model = model;   // model = model 이라고 하면 에러난다.
       this.color = color;
       this.maxSpeed = maxSpeed;
    }

}


 

2. 클래스 내부에서 오버로딩된 다른 생성자를 호출할 때


1  package Practice;
2  
3  public class Car {

4
5      String model;
6      String color;
7      int maxSpeed;
8
9      Car(String model, String color) {

10          this(model, color, 200);   // 오버로딩된 다른 생성자 불러오기
11      }

12
13     Car(String model, String color, int maxSpeed) {  // 오버로딩한 생성자

14

15         // 좌변은 필드값, 우변은 파라미터값
16         this.model = model;
17         this.color = color;
18         this.maxSpeed = maxSpeed;

19      }
20  }


9번 라인부터인 Car(String modelString color) 생성자에서

굳이,

 

this.model = model;
this.color = color;
this.maxSpeed = 200;

 

이라고 다 쓸 필요없이

오버로딩했던 생성자를 끌어다가

this(model, color, 200); 이렇게 쓰면 된다.

 

이렇게 클래스 내부에서 오버로딩했던 생성자를 끌어오기 위해서는 this 키워드가 필요하다

 

 

 

3. 객체 자신의 참조값을 전달하고 싶을 때


package Practice;

public class Car {


    String model;
    String color;
    int maxSpeed;


    Car(String model, String color, int maxSpeed) {


        // 좌변은 필드값, 우변은 파라미터값
        this.model = model;
        this.color = color;
        this.maxSpeed = maxSpeed;
    }


    public Car getCarInstance() {
        return this; // 메소드의 리턴값으로 객체 자기 자신의 참조값을 전달하고 싶을 때 
    }

}


 

반응형