Super Keyword in Java

 

🔹 super Keyword in Java

The super keyword is used in a subclass to refer to members (variables or methods) of its immediate superclass.

✅ Uses of super:

  1. Access superclass constructor

  2. Access superclass methods

  3. Access superclass variables


1. Using super() to Call Superclass Constructor

By default, when a subclass constructor is called, it implicitly calls the no-argument constructor of the superclass using super().


class Animal { Animal() { System.out.println("Animal constructor called"); } } class Dog extends Animal { Dog() { super(); // optional here, Java adds it automatically System.out.println("Dog constructor called"); } } public class Main { public static void main(String[] args) { Dog d = new Dog(); } }

Output:


Animal constructor called Dog constructor called

2. Using super to Access Superclass Method


class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { super.sound(); // calling superclass method System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Dog d = new Dog(); d.sound(); } }

3. Using super to Access Superclass Variable


class Animal { String name = "Animal"; } class Dog extends Animal { String name = "Dog"; void printNames() { System.out.println(name); // Dog System.out.println(super.name); // Animal } } public class Main { public static void main(String[] args) { Dog d = new Dog(); d.printNames(); } }

🔹 Order of Constructor Calls in Inheritance

In Java, when a subclass object is created:

  1. Superclass constructor is called first

  2. Then the subclass constructor is called

This ensures that the parent part of the object is initialized before the child part.

📌 Example:


class A { A() { System.out.println("Constructor of A"); } } class B extends A { B() { System.out.println("Constructor of B"); } } class C extends B { C() { System.out.println("Constructor of C"); } } public class Main { public static void main(String[] args) { C obj = new C(); } }

Output:


Constructor of A Constructor of B Constructor of C

✅ Even though we only created an object of class C, constructors of B and A are called first, in that order.


📌 Summary

ConceptDescription
super()Calls the immediate superclass constructor. Must be the first statement in subclass constructor.
super.method()Calls a method from the superclass.
super.variableAccesses a variable from the superclass (if hidden by subclass variable).
Constructor Call OrderParent constructor → Child constructor

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Java Compiler and Java Virtual Machine