First we will know in which scenario we use super keyword. When the super class property and sub class property is exactly same then in that context to access super class property, we use super keyword.
The keyword super that can be used to access super class variable as super.variable
The keyword super that can be used to access super class method as super.method();
The keyword super that can be used to access super class constructor as super();
To access super class variable:
InheritanceExample3.java
package com.inheritance;
class A //A : Super class
{
int x=100;
}
class B extends A //B : Sub class
{
int x=200;
void get()
{
System.out.println("x="+super.x);
System.out.println("x="+x);
}
}
public class InheritanceExample3
{
public static void main(String[] args)
{
B obj=new B();
obj.get();
}
}
Output
x=100
x=200
To access super class method:
InheritanceExample4.java
package com.inheritance;
class Vehicle
{
void journey()
{
System.out.println("Journey by Vehicle");
}
}
class Car extends Vehicle
{
void journey() //Method Overridding
{
super.journey();
System.out.println("Journey by Car");
}
}
public class InheritanceExample4 {
public static void main(String[] args)
{
Car c=new Car();
c.journey();
}
}
output:
Journey by Vehicle
Journey by Car
To access super class constructor:
InheritanceExample5.java
package com.inheritance;
class Parent
{
Parent()
{
System.out.println("super class constructor");
}
}
class Child extends Parent
{
Child()
{
super(); //To access super class constructor
System.out.println("sub class constructor");
}
}
public class InheritanceExample5 {
public static void main(String[] args)
{
Child obj=new Child();
}
}
output
super class constructor
sub class constructor
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc