[JAVA 객체지향프로그래밍] this

    반응형

     

    이 글은 패스트 캠퍼스 한번에 끝내는 Java/Spring 웹 개발 마스터 초격차 패키지 강의를 듣고 공부한 내용을 바탕으로 정리한 글입니다.


     

    1. this

    this는 인스턴스 자신의 메모리를 가리킵니다. 즉, 자신의 주소(참조값)을 리턴합니다. this는 생성자에서 또 다른 생성자를 호출할 때 사용됩니다.

    this: 클래스 안에서 참조변수가 가지는 주소 값과 동일한 주소값을 가지는 키워드

    2. 생성자에서 다른 생성자를 호출

    클래스에서 생성자가 여러 개인 경우, this를 이용하여 생성자에서 다른 생성자를 호출할 수 있습니다.

    생성자에서 다른 생성자를 호출하는 경우, 인스턴스의 생성이 완전하지 않은 상태이므로 this() statement 이전에 다른 statement를 쓸 수 없습니다.

    public class Person {
    
        String name;
        int age;
    
        public Person() {
            this("이름없음", 1);
        }
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    위의 코드에서 Person의 default constructor는 생성자 안에서 this를 이용하여 nameage를 매개변수로 갖는 생성자를 호출합니다.

    3. 자신의 주소를 반환

    public class Person {
    
        String name;
        int age;
    
        public Person() {
            this("이름없음", 1);
        }
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public Person getPerson() {
            return this;
        }
    
    
        public static void main(String[] args)
        {
            Person p = new Person();
            p.name = "James";
            p.age = 37;
    
            Person p2 = p.getPerson();
            System.out.println(p);
            System.out.println(p2);
        }
    }

    getPerson()의 반환값을 찍어보면 객체 자신이 반환됨을 확인할 수 있습니다.

    반응형

    댓글