Inheritance in Java

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Inheritance is one of the key features of Object Oriented Programming. Inheritance provided mechanism that allowed a class to inherit property of another class. When a Class extends another class it inherits all non-private members including fields and methods. Inheritance in Java can be best understood in terms of Parent and Child relationship, also known as Super class(Parent) and Sub class(child) in Java language.

Inheritance defines is-a relationship between a Super class and its Sub class. extends and implements keywords are used to describe inheritance in Java.

Example: Developer is the subclass and Employee is the superclass. Relationship between two classes is Developer IS-A Employee. It means that Developer is a type of Employee.
class Employee{
 float salary=40000;
class Developer extends Employee{
 int bonus=10000;
 public static void main(String args[]){
   Developer d=new Developer();
   System.out.println("Developer salary is:"+d.salary);
   System.out.println("Bonus of Programmer is:"+d.bonus);
 Developer salary is:40000.0
 Bonus of Developer is:10000

Purpose of Inheritance

  • To promote code reuse.
  • To use Polymorphism.

Simple example of Inheritance

class Parent
public void p1()
System.out.println("Parent method");
public class Child extends Parent {
public void c1()
System.out.println("Child method");
public static void main(String[] args)
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class 


Child method
Parent method
Below is not possible using java class Inheritance

1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.

2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.

3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.

4. A subclass can extend only one superclass