DEV Community

Elayaraj C
Elayaraj C

Posted on

My understanding in java Inheritance & super()

It allows a class (called a subclass or child class) to inherit fields and methods from another class (called a superclass or parent class).
๐Ÿ”น Why Use Inheritance?

  • Reusability: Reuse code from existing classes.
  • Extensibility: Extend or add new features to existing classes.
  • Maintainability: Easier to manage code.
  • Polymorphism: Allows a subclass to be treated as an instance of its superclass. ๐Ÿ”ธ Basic Syntax
class Parent {
    void display() {
        System.out.println("This is the parent class");
    }
}

class Child extends Parent {
    void show() {
        System.out.println("This is the child class");
    }
}

public class Main {
    public static void main(String[] args) {
        Child obj = new Child();
        obj.display();  // Inherited method
        obj.show();     // Child's own method
    }
Enter fullscreen mode Exit fullscreen mode

}

๐Ÿ”น Types of Inheritance in Java

Single Inheritance

-One class inherits from another.

Multilevel Inheritance

    A class inherits from a derived class.
Enter fullscreen mode Exit fullscreen mode

Hierarchical Inheritance

    Multiple classes inherit from a single parent class.

โŒ Multiple Inheritance (via classes) is not supported in Java (to avoid ambiguity issues like the Diamond Problem).
Enter fullscreen mode Exit fullscreen mode

โœ… But Java supports multiple inheritance using interfaces.

๐Ÿ”ธ super Keyword
Used to:

Access superclass methods or constructors.

class Parent {
    void greet() {
        System.out.println("Hello from parent");
    }
}

class Child extends Parent {
    void greet() {
        super.greet(); // Call parent version
        System.out.println("Hello from child");
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ธ Access Modifiers in Inheritance

  • private: Not accessible in child class.
  • protected: Accessible in child class, even if it's in a different package.
  • public: Always accessible.
  • default (no modifier): Accessible in the same package only.

๐Ÿ”น Why We Use super() in Java:

  1. To call the parent class constructor:
  • When a subclass is created, it often needs to initialize things from its parent class. super() lets you do that.
  • It must be the first statement in the subclass constructor.
  1. To reuse parent class initialization code, instead of rewriting it in the child class.

๐Ÿ”ธ When you don't write super() explicitly:

Java automatically inserts a default super() call if thereโ€™s no constructor with parameters in the parent class.
๐Ÿ”น Other Forms of super (not super()) **(tbd)**

Besides super() (constructor call), Java also allows:

  • super.someMethod() โ†’ Call a method from the parent class.
  • super.someVariable โ†’ Access a variable from the parent class.

Top comments (0)