IT 정보/Java

[Java] super 와 super()의 차이

개발하는 동그리 2022. 5. 12. 13:42
728x90
반응형

super

this와 동일하게 참조변수 형이며, 상위클래스의 객체를 불러온다. (ex. super.name or super.id )
상위 클래스와 하위클래스의 변수가 같은 경우에 구분하기 위한 키워드로 사용된다. 

public class Super {
    public static void main(String[] args) {
        Lower lower = new Lower();
        lower.classInfo();
    }
}

class Upper {
    int count = 40; // super.count
}

class Lower extends Upper {
    int count = 20; // this.count

    void classInfo() {
        System.out.println("count = " + count);
        System.out.println("this.count = " + this.count);
        System.out.println("super.count = " + super.count);
    }
}

//Output
count = 20
count = 20
count = 40

 

 

super()

this() 와 유사하게 사용되지만, 다른점은 상위 클래스의 생성자를 호출한다는 것이다. 

사용 조건 

  • this() 메서드와 마찬가지로 생성자 내부에 첫줄에 존재해야 한다.
  • 중요한 사실 : 모든 생성자의 첫 줄에는 반드시 this() or super() 이 선언되어야 한다. (잘 모르겠음)

 

모든 클래스를 생성할 때에는 기본생성자를 습과화 하자!! 

728x90
반응형