Inheritance in Java
![]() |
Inheritance |
Inheritance is the core concept of object-oriented programming. The primary application of Inheritance is organizing and structuring of large software applications.
Inheritance is a tool to apply code reuse, reduced complexity, high manageability of software application implementation. Inheritance is required and necessary to induct Polymorphism in Java. Inheritance can be defined as “Acquisition of the data and behavior of one class from other”(deriving subclass from a superclass).
Inheritance introduces Hierarchical implementation(generalization and specialization). Inheritance represents the IS-A relationship.
Generalization Vs Specialization
![]() |
Generalization Vs Specialization |
Java uses a single inheritance model, it means subclass can have one(and only one) superclass. Excepting Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of the Object class. The “extends” keyword is used to implement inheritance. A subclass inherits all the members (fields, methods, and nested classes) from its superclass, except constructors.
![]() |
Types of inheritance available in Java |
![]() |
Types of inheritance not available in Java |
The super Keyword
- The keyword “super” if present it must be the first statement to be executed in a constructor.
- this(argList) refers to current class constructor.
- super(argList) refers to the immediate superclass constructor
- The order of the invocation of the constructor follows a class hierarchy.
- If none of the super or this constructor is inserted than compiler automatically inserts super() which is a superclass no-arg constructor.
Example:( Inheritance in java)
public class A { //super class int x; static int z=12; static void display() { System.out.println("i ma in A"); } A()// empty constructor { } A(int x){// constructor with fields this();//calling empty constructor implicitly this.x=x; } void displayX()//method { System.out.println("X="+this.x); } } /********************************************/ public class B extends A{//sub class B(int x,int y) { super(x);//super must be in first line only this.y=y; } int y; static int z=21; static void display() { System.out.println("i am in B"); } // B also has inherited x and displayX() from A void displayY() { System.out.println("Y="+this.y); } } /************************************************************************/ public class Demo { public static void main(String[] args) { B b=new B(15,20); b.displayX(); b.displayY(); b.display(); } } /*********************************************/ Output: X=15 Y=20 i am in B