자바 클래스와 객체 2

신범철·2022년 1월 1일
0

자바

목록 보기
2/17

머리말

이글은 자바를 빠르게 끝내기 위해 내가 헷갈리는 부분만을 정리해논 글입니다. Do it! 자바 프로그래밍 입문을 정리하지만 내용을 많이 건너뜀

this 예약어

this란

  • 클래스 코드에서 사용하는 this는 생성된 인스턴스 자신을 가르키는 역할
  • 생성자에서 다른 생성자를 호출할 때 사용
  • 인스턴스가 자기 자신의 주소를 반환할 때 사용

생성된 인스턴스 자신을 가르키는 this

생성자에서 다른 생성자를 호출하는 this

package doit;

class Person{
    String name;
    int age;

    Person(){
        this("이름 없음",1);//this를 사용해 Person(String, int) 생성자 호출
    }

    Person(String name, int age){
        this.name = name;
        this.age = age;

    }
}

public class Test {
    public static void main(String[] args){
        Person noName = new Person();
        System.out.println(noName.name);
        System.out.println(noName.age);
    }
}

위와같이 this는 자기자신을 가르치는 것 외에도 this("이름 없음",1)이와 같이 아래 생성자를 호출하는 역할로도 사용가능하다.

자신의 주소를 반환하는 this

생성된 클래스 자신의 주소값을 반환할 수 있다.
인스턴스 주소값을 반환할때는 this
반환형은 클래스 자료형을 사용한다.

package doit;

class Person{
    String name;
    int age;

    Person(){
        this("이름 없음",1);
    }

    Person(String name, int age){
        this.name = name;
        this.age = age;

    }
    Person returnItSelf(){
        return this;
    }
}

public class Test {
    public static void main(String[] args){
        Person noName = new Person();
        System.out.println(noName.name);
        System.out.println(noName.age);

        Person p = noName.returnItSelf();//this값을 클래스변수에 대입
        System.out.println(p); // noName.returnItSelf()의 반환 값 출력
        System.out.println(noName);//참조 변수 출력
    }
}

출력결과

profile
https://github.com/beombu

0개의 댓글