수색…


예제와 함께 훌륭한 키워드 사용

슈퍼 키워드는 3 곳에서 중요한 역할을 수행합니다.

  1. 생성자 레벨
  2. 방법 수준
  3. 가변 수준

생성자 레벨

super 키워드는 부모 클래스 생성자를 호출하는 데 사용됩니다. 이 생성자는 기본 생성자 또는 매개 변수화 된 생성자가 될 수 있습니다.

  • 기본 생성자 : super();

  • 매개 변수화 된 생성자 : super(int no, double amount, String name);

     class Parentclass
     {
        Parentclass(){
           System.out.println("Constructor of Superclass");
        }
     }
     class Subclass extends Parentclass
     {
        Subclass(){
         /* Compile adds super() here at the first line
          * of this constructor implicitly
          */
         System.out.println("Constructor of Subclass");
        }
        Subclass(int n1){
         /* Compile adds super() here at the first line
          * of this constructor implicitly
          */
         System.out.println("Constructor with arg");
        }
        void display(){
         System.out.println("Hello");
        }
        public static void main(String args[]){
         // Creating object using default constructor
         Subclass obj= new Subclass();
         //Calling sub class method 
            obj.display();
            //Creating object 2 using arg constructor
            Subclass obj2= new Subclass(10);
            obj2.display();
       }
     }
    

참고 : super() 가 생성자의 첫 번째 문이어야합니다. 그렇지 않으면 컴파일 오류 메시지가 표시됩니다.

방법 수준

super 키워드는 메소드 재정의 (override)의 경우에도 사용할 수 있습니다. super 키워드는 부모 클래스 메소드를 호출하거나 호출하는 데 사용할 수 있습니다.

class Parentclass
{
   //Overridden method
   void display(){
    System.out.println("Parent class method");
   }
}
class Subclass extends Parentclass
{
   //Overriding method
   void display(){
    System.out.println("Child class method");
   }
   void printMsg(){
    //This would call Overriding method
    display();
    //This would call Overridden method
    super.display();
   }
   public static void main(String args[]){        
    Subclass obj= new Subclass();
    obj.printMsg(); 
   }
}

참고 : 메소드 오버라이드가없는 경우 부모 클래스 메소드를 호출 할 때 super 키워드를 사용할 필요가 없습니다.

가변 수준

super 는 직접적인 부모 클래스 인스턴스 변수를 참조하는 데 사용됩니다. 상속의 경우에는 기본 클래스의 가능성이있을 수 있으며 파생 클래스는 유사한 데이터 멤버를 가질 수 있습니다. 기본 / 부모 클래스 및 파생 된 / 자식 클래스의 데이터 멤버를 구별하기 위해 파생 클래스의 컨텍스트에서 기본 클래스 데이터 회원은 반드시 super 키워드 앞에 와야합니다.

//Parent class or Superclass
class Parentclass
{
    int num=100;
}
//Child class or subclass
class Subclass extends Parentclass
{
    /* I am declaring the same variable 
     * num in child class too.
     */
    int num=110;
    void printNumber(){
     System.out.println(num); //It will print value 110
     System.out.println(super.num); //It will print value 100
    }
    public static void main(String args[]){
       Subclass obj= new Subclass();
       obj.printNumber();    
    }
}

참고 : 기본 클래스 데이터 멤버 이름 앞에 super 키워드를 쓰지 않으면 현재 클래스 데이터 멤버로 참조되고 기본 클래스 데이터 멤버는 파생 클래스 컨텍스트에서 숨겨집니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow