Java program to demonstrate super keyword
Program
class Base
{
int i = 10;
Base()
{
System.out.println("Base class constructor");
}
}
class Derieved extends Base
{
int i = 100;
Derieved()
{
super();
System.out.println("Derieved class constructor");
}
void showSuper()
{
System.out.println("From Super class:\t" + super.i);
System.out.println("From derieved class:\t" + i);
}
}
class SuperDemo
{
public static void main(String[] args)
{
Derieved a = new Derieved();
a.showSuper();
}
}
This program demonstrates the use of the super keyword in Java, which allows a subclass to access members and constructors of its parent class.
-
Classes and Inheritance:
Base: The parent class with an instance variableiand a constructor that prints a message.Derived: The subclass ofBase. It also has an instance variablei(shadowing the parent class variable) and a constructor that explicitly calls the parent class's constructor usingsuper().
-
Key Concepts:
super.i: Refers to theivariable of the parent class.i: Refers to theivariable of the current (derived) class.super(): Calls the parent class's constructor explicitly to initialize its state.
-
Execution:
- The
Derivedclass constructor calls theBaseclass constructor usingsuper()before executing its own body. - The
showSuper()method demonstrates how thesuperkeyword is used to access theivariable of the parent class, distinguishing it from the subclass variable.
- The
Steps:
-
When an object of
Derivedis created:- The
Baseclass constructor is called first, printing:
"Base class constructor" - Then the
Derivedclass constructor is executed, printing:
"Derived class constructor"
- The
-
When the
showSuper()method is called:- The value of the parent class's
iis accessed usingsuper.iand printed:
"From Super class: 10" - The value of the derived class's
iis printed:
"From Derived class: 100"
- The value of the parent class's
Key Features of super:
-
Accessing Parent Class Members:
- Allows a subclass to access the variables and methods of its parent class when they are shadowed by the subclass.
-
Calling Parent Class Constructor:
- Ensures that the parent class's constructor is executed first, initializing any inherited state.
-
Usage:
- Used in constructors or methods of a subclass to reference parent class behavior.
Example Use Case:
The super keyword is particularly useful in inheritance to avoid confusion when subclass members shadow parent class members or when initializing inherited attributes through the parent constructor.
Output
Base class constructor
Derieved class constructor
From Super class: 10
From derieved class: 100