본문 바로가기
Language/Java

Super

by Zayne 2023. 5. 11.

'super' keyword is used to refer to the parent class.

It is generally used with methods and variables, and is also used in constructors.

 

Here is an example with methods:

class ParentClass {
    void display() {
        System.out.println("This is the parent class");
    }
}

class ChildClass extends ParentClass {
    void display() {
        System.out.println("This is the child class");
    }

    void printMsg() {
        // Calling the display() method of parent class
        super.display();
        // Calling the display() method of this class
        display();
    }
}

public class Main {
    public static void main(String args[]) {
        ChildClass obj = new ChildClass();
        obj.printMsg();
    }
}

 

in this example, when 'obj.printMsg()' is called, it will output:

This is the parent class
This is the child class

 

Here is an example with constructors:

class ParentClass {
    ParentClass() {
        System.out.println("Constructor of Parent");
    }
}

class ChildClass extends ParentClass {
    ChildClass() {
        super();
        System.out.println("Constructor of Child");
    }
}

public class Main {
    public static void main(String args[]) {
        ChildClass obj = new ChildClass();
    }
}

 

in this example, when 'new ChildClass()' is called, it will output:

Constructor of Parent
Constructor of Child

 

This is because the 'super()' in the child's constructor calls the parent's constructor.

If 'super()' is not explicitly called, Java will insert a no-argument call to 'super()' for you as the first line in the constructor.

'Language > Java' 카테고리의 다른 글

Java Collections Framework  (0) 2023.05.25
Java access modifiers  (0) 2023.05.24
다형성(Polymorphism)  (0) 2023.05.07
스트림  (0) 2023.03.08
Optional 클래스  (0) 2023.03.07