×
☰ See All Chapters

super keyword in Java

super is reference variable which refers to the immediate super class object. super keyword is used to access the instance members of the super class from sub class and cannot be used to access the static members of the class or super keyword cannot be used in static context. super is used to access the following members of the super class from subclass.

    1. Variables 

    2. Methods 

    3. Constructors 

super to access variables

All the members of super class will be inherited into subclass (except constructor and private members) and can be accessed directly in subclass. If subclass has the variable with the same name as in super class, it creates name conflict. super keyword is used to resolve the conflict between super class instance variables and subclass instance variables

class Employee {

        String name = "Manu";

}

 

class Manager extends Employee {

        String name = "Manu Manjunatha";

 

        void printName () {

                System.out.println(name);// prints Manu

                System.out.println(super.name);// prints Manu Manjunatha

        }

}

super to access methods

If subclass has the method with the same name as in super class, it creates name conflict. super keyword is used to resolve the conflict between super class instance methods and subclass methods.

class Employee {

        String name = "Manu";

        public String displayName() {

                System.out.println(name );

        }

}

 

class Manager extends Employee {

        String name = "Manu Manjunatha";

        public String displayName() {

                System.out.println(name );

        }

        void printName() {

                displayName();// prints Manu Manjunatha

                super.displayName();// prints Manu

        }

}

super to access constructor

When a subclass object is created, first it invokes superclass constructor, then subclass constructor. To create subclass object it is mandatory to invoke super class constructor. So to invoke superclass constructor super() is used. super( ) keyword should be used in the first line of the sub class constructor.  Compiler will add super() into the default constructor of subclass.  This default super() will invoke default constructor of super class. super() can be called with arguments if you want to invoke super class parameterized constructor.

class Box {

        int height;

        int width;

        int length;

 

        public Box() {

        }

 

        public Box(int height, int width, int length) {

                this.height = height;

                this.width = width;

                this.length = length;

        }

 

}

 

class BoxWeight extends Box {

        int depth;

 

        public BoxWeight(int height, int width, int length, int depth) {

                super(height, width, length);

                this.depth = depth;

        }

}

 


All Chapters
Author