Variables and methods of super class can be overridden in subclass. In case of overriding, a subclass object call its own variables and methods. Subclass cannot access the variables and methods of super-class because the overridden variables or methods hides the methods and variables of super class.
But still java provides a way to access super class members even if its members are overridden. Super is used to access super-class variables, methods, constructors.
Super can be used in three forms :
- First form is for calling super class constructor.
- Second one is to call super class variables.
- Third one is to call super class methods.
Example (calling super class constructor):-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/* superclass vehicle */ class Vehicle { Vehicle() { System.out.println("Vehicle class Constructor"); } } /* subclass Car extending the Vehicle class */ class Car extends Vehicle { Car() { // invoke or call parent class constructor super(); System.out.println("Car class Constructor"); } } /* Driver program to test*/ class Test { public static void main(String[] args) { Car c = new Car(); } } |
Output:-
1 2 |
Vehicle class Constructor Car class Constructor |
Example (call super class variables):-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* Base class vehicle */ class Vehicle { int maxSpeed = 100; } /* 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 car = new Car(); car.display(); } } |
Output:-
1 |
Maximum Speed: 100 |
Example (call super class methods):-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/* Base class Vehicle */ class Vehicle { void show() { System.out.println("This is Vehicle class"); } } /* Subclass Car */ class Car extends Vehicle { void show() { System.out.println("This is Car class"); } // Note that display() is only in Student class void display() { // will invoke or call current class show() method show(); // will invoke or call parent class show() method super.show(); } } /* Driver program to test */ class Test { public static void main(String args[]) { Car c = new Car(); // calling show() of Car c.display(); } } |
Output:-
1 2 |
This is Vehicle class This is Car class |