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.

  1. Classes and Inheritance:

    • Base: The parent class with an instance variable i and a constructor that prints a message.
    • Derived: The subclass of Base. It also has an instance variable i (shadowing the parent class variable) and a constructor that explicitly calls the parent class's constructor using super().
  2. Key Concepts:

    • super.i: Refers to the i variable of the parent class.
    • i: Refers to the i variable of the current (derived) class.
    • super(): Calls the parent class's constructor explicitly to initialize its state.
  3. Execution:

    • The Derived class constructor calls the Base class constructor using super() before executing its own body.
    • The showSuper() method demonstrates how the super keyword is used to access the i variable of the parent class, distinguishing it from the subclass variable.

Steps:

  1. When an object of Derived is created:

    • The Base class constructor is called first, printing:
      "Base class constructor"
    • Then the Derived class constructor is executed, printing:
      "Derived class constructor"
  2. When the showSuper() method is called:

    • The value of the parent class's i is accessed using super.i and printed:
      "From Super class: 10"
    • The value of the derived class's i is printed:
      "From Derived class: 100"

Key Features of super:

  1. Accessing Parent Class Members:

    • Allows a subclass to access the variables and methods of its parent class when they are shadowed by the subclass.
  2. Calling Parent Class Constructor:

    • Ensures that the parent class's constructor is executed first, initializing any inherited state.
  3. 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