Java this

김정훈·2024년 4월 17일

Java

목록 보기
13/48

this


  • 모든메서드에 존재하는 지역변수
  • 객체의 자원을 접근하기 위해서 객체의 주소값이 담겨있음.
  • 객체의 자원을 소비하기위한 수단
package exam01;
public class Ex01 {
    public static void main(String[] args) {
        Schedule s1 = new Schedule();

        s1.setYear(2024);
        s1.setMonth(2);
        s1.setDay(40);

        s1.printThis();
        //> exam01.Schedule@10f87f48
        System.out.println(s1);
        //> exam01.Schedule@10f87f48
    }
}
//Schedule의 this를 출력하면 s1과 같다.
//this와 s1은 똑같은 주소를 가르키고 있다.

public void setYear(int year) {
        this.year = year;
        //this.year은 힙에 있는 멤버변수
        //year은 스택에 있는 변수(메서드 내부에 있는 지역변수)
    }

  • 지역변수
    - 생성된 객체의 주소값
    - 인스턴스 메서드의 지역변수
    - 메서드 내부에서 객체의 자원을 접근하기 위한 주소값

  • 메서드 : this(...)
    - 클래스 내부에서 정의된 생성자를 호출
    • 객체생성X, 생성자에 정의한 코드를 실행
    • 생성자 메서드 내부에서 주로 사용
      - 생성자 메서드를 다른 생성자에서 호출
      - 생성자 메서드의 첫번째 라인 에서만 정의 가능
    public Schedule(){
           this(2024,4,17);
       }
       public Schedule (int year, int month, int day){
           this.year = year;
           this.month = month;
           this.day = day;
       }

profile
안녕하세요!

0개의 댓글