Java super Keyword

🔹 Java super Keyword

The super keyword in Java is a reference variable that refers to the immediate parent class object. It is used to access parent class members (variables, methods, and constructors) from a child class.


✅ 1. Uses of super Keyword

  1. Access parent class variables

  2. Call parent class methods

  3. Call parent class constructor (constructor chaining)


✅ 2. Example 1: Access Parent Class Variables

class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = “Dog”;

void printNames() {
System.out.println(name); // Dog’s name
System.out.println(super.name); // Animal’s name
}
}

public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.printNames();
}
}

📌 Output:

Dog
Animal

super.name accesses the parent class variable when overridden by child class.


✅ 3. Example 2: Call Parent Class Methods

class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void eat() {
System.out.println(“Dog eats”);
}

void show() {
eat(); // Dog’s eat()
super.eat(); // Animal’s eat()
}
}

public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.show();
}
}

📌 Output:

Dog eats
Animal eats

super.eat() calls the method from parent class even if it is overridden.


✅ 4. Example 3: Call Parent Class Constructor

class Animal {
Animal() {
System.out.println("Animal constructor called");
}
}
class Dog extends Animal {
Dog() {
super(); // call parent constructor
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

super() must be the first statement in the child class constructor.


✅ 5. Key Points About super

Usage Description
super.variable Access parent class variable
super.method() Call parent class method
super() Call parent class constructor (must be first line)
When necessary Helps avoid ambiguity when members are overridden
  • Used in inheritance to access hidden members of parent class.

  • Can be combined with polymorphism to manage overridden methods.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *