super() in Java

前端 未结 15 2312
逝去的感伤
逝去的感伤 2020-11-22 05:36

Is super() used to call the parent constructor? Please explain super().

15条回答
  •  星月不相逢
    2020-11-22 05:56

    I would like to share with codes whatever I understood.

    The super keyword in java is a reference variable that is used to refer parent class objects. It is majorly used in the following contexts:-

    1. Use of super with variables:

    class Vehicle 
    { 
        int maxSpeed = 120; 
    } 
    
    /* sub class Car extending vehicle */
    class Car extends Vehicle 
    { 
        int maxSpeed = 180; 
    
        void display() 
        { 
            /* print maxSpeed of base class (vehicle) */
            System.out.println("Maximum Speed: " + super.maxSpeed); 
        } 
    } 
    
    /* Driver program to test */
    class Test 
    { 
        public static void main(String[] args) 
        { 
            Car small = new Car(); 
            small.display(); 
        } 
    } 
    

    Output:-

    Maximum Speed: 120
    
    1. Use of super with methods:
    /* Base class Person */
    class Person 
    { 
        void message() 
        { 
            System.out.println("This is person class"); 
        } 
    } 
    
    /* Subclass Student */
    class Student extends Person 
    { 
        void message() 
        { 
            System.out.println("This is student class"); 
        } 
    
        // Note that display() is only in Student class 
        void display() 
        { 
            // will invoke or call current class message() method 
            message(); 
    
            // will invoke or call parent class message() method 
            super.message(); 
        } 
    } 
    
    /* Driver program to test */
    class Test 
    { 
        public static void main(String args[]) 
        { 
            Student s = new Student(); 
    
            // calling display() of Student 
            s.display(); 
        } 
    }
    

    Output:-

    This is student class
    This is person class
    

    3. Use of super with constructors:

    class Person 
    { 
        Person() 
        { 
            System.out.println("Person class Constructor"); 
        } 
    } 
    
    /* subclass Student extending the Person class */
    class Student extends Person 
    { 
        Student() 
        { 
            // invoke or call parent class constructor 
            super(); 
    
            System.out.println("Student class Constructor"); 
        } 
    } 
    
    /* Driver program to test*/
    class Test 
    { 
        public static void main(String[] args) 
        { 
            Student s = new Student(); 
        } 
    } 
    

    Output:-

    Person class Constructor
    Student class Constructor
    

提交回复
热议问题