course 2021/JAVA

day11 - this, super

코딩하는토끼 2021. 8. 31. 23:54

> this 

자기자신 객체를 지정할 때 사용하는 키워드

this. - 동일 클래스 내의 멤버(멤버변수, 메소드) 지정

this() - 생성자 내에서 자신의 다른 생성자 호출

public class Person { 
    String name;  //멤버변수
    int age;
    
    Person(String name, int age) {  //생성자, 매개변수 name, age가 위의 멤버변수 이름과 같음
        name = name;  //앞의 name이 멤버변수가 아닌 가까이 있는 매개변수로 인식됨 (이름이 같기 때문)
        age = age;
    }
}


//this. 를 사용하여 수정한 코드
public class Person {
    String name;
    int age;
    
    Person(String name, int age) {
        this.name = name;  //this.를 사용하여 앞의 name이 멤버변수를 지칭할 수 있게 해줌
        this.age = age;
    }
    
    //this. 를 사용하여 같은 클래스에 있는 메소드 지정
    String info() {
        return "이름: " + name + ", 나이: " + age;
    }
    System.out.println( this.info() ); //this.를 사용하여 info 메소드 지정 - 여기에서는 this.를 쓰지 않아도 문제없음
}
public class Person {
    String name;
    int age;
    
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    Person(String name) {
        this.name = name;
        this.age = 1;
    }
    
    Person() {
        this.name = "홍길동";
        this.age = 1;
    }
}


//this()를 사용하여 위의 코드를 간단히    
public class Person {
    String name;
    int age;
    
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    Person(String name) {
        this(name, 1);  //this() 로 위의 생성자 호출
    }
    
    Person() {
        this("홍길동", 1);  //this() 로 위의 생성자 호출
    }
}

> super

한 단계 위 부모클래스의 객체를 지정할 때 사용하는 키워드

super. - 부모클래스의 멤버(멤버변수, 메소드) 지정

super() - 생성자 내에서 부모클래스의 생성자를 호출

this(), super()는 생성자의 첫 라인에 써주어야 함

*this(), super()를 쓰지 않는 경우, 자동으로 super()가 삽입되어 부모클래스의 기본생성자가 호출됨

*상속의 계층구조는 super()을 통한 호출로 연결되어있음

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

public class Mother extends Person {  //상속 (부모클래스 Person, 자식클래스 Mother) 
    Mother() {  //생성자
        super("김여사", 63);  //부모클래스에 기본생성자가 없으므로 매개변수 입력해줌
    }
}