this 란?

this의 특징

  1. 객체 자신에 대한 참조값을 가진다. (자기 자신을 가리킨다.)

  2. 메소드 내에서만 사용된다.

  3. 객체 자신을 메소드에 전달하거나 리턴하기 위해 사용된다.

  4. static 메소드에서는 사용할 수 없다.

  5. this.맴버변수

    : 매개 변수와 객체 자신이 가지고 있는 변수의 이름이 같은 경우,이를 구분하기 위해 this를 붙인다.

    public class Example {
    	private String ocean;
    	private String land;
    	private String people;
    	
    	public void makingCountry(String ocean, String land, String people) {
    		// 맴버 변수 = 매개 변수
    		this.ocean = ocean;
    		this.land = land;
    		this.people = people;
    	}
    }
    

<aside> 💡

Tip. 맴버 변수와 메서드의 매개변수의 이름이 같으면 둘을 어떻게 구분해야 할까?

이 경우, 맴버 변수보다 매개변수가 코드 블럭의 더 안쪽에 있기 때문에 매개변수가 우선순위를 가진다. 맴버 변수에 접근하려면 앞에 this. 이라고 해주면 된다. 여기서 this는 인스턴스 자신의 참조값을 가리킨다.

</aside>

  1. this()

    : 해당 클래스의 기본 생성자를 호출한다.

    public class Sandwitch {
    	public String bread; 
    	public String vegetable;
    	public String meat; 
    	public Stirng source; 
    	
    	// 기본 생성자
    	public Sandwitch() {
    		this.bread = "플랫브래드";
    		this.vegetable = "양상추";
    		this.meat = "폴드포크 바비큐";
    		this.source = "랜치";
    	}
    	
    	// 빵 종류만 인자로 받는 생성자
    	public Sandwitch(String bread) {
    		this();
    		this.bread = bread;
    	}
    }
    
  2. this(매개변수)

    : 생성자 내에서 다른 생성자를 호출한다.

    public class Sandwitch {
    	public String bread; 
    	public String vegetable;
    	public String meat; 
    	public Stirng source; 
    	
    	
    	public Sandwitch() {
    		this("flatBread", "lettuce", "chicken", "mustard")
    	}
    	
    	public Sandwitch(String bread, String vegetable, String meat, String source) {
    		this.bread = bread;
    		this.vegetable = vegetable;
    		this.meat = meat;
    		this.source = source;
    	}
    	
    }
    

진행 과정