Inheritance is one of the cornerstones of OOPS(Object oriented Programming language) because  of the fact that it allows the creation of hierarchical classifications.

We can create a general class that defines traits common to a set of related items. This class can then be inherited by other class, each adding those things that are unique. A class that is inherited is called a Superclass.

The class that does the inheriting is called a Subclass. That  is why a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and add its own, unique elements.

inheritance in Java Programming

Inheritance basics-

For inheriting a class, we simply incorporate the definition of one class into another by using the extends keyword.

To understand it more, let’s do it practically

The following program is in JAVA and it creates a superclass named A and a subclass named B.Java Inheritance example


// A simple example of inheritance.

// Creating a superclass

class A{

int i, j ;

void showij() {

System.out.println(“ i and j:” + “ “ + j) ;



// Creating a subclass by extending class A.


class B extends A{

int k ;


void  showk(){

System.out.println(“ K: “ + k);



void sum() {

System.out.println(“i + j + k :” + (i+j+k)) ;





public static void main(String args[]) {

A superOb = new A();

B subOb = new B();


// Superclass can be used itself.


superOb.i = 10 ;

superOb.j = 20 ;

System.out,println(“Contents of superOb:”) ;

superOb.showij () ;

System.out.println() ;


/* The subclass has access to all public members of its superclass */


subOb.i =7 ;

subOb.j = 8 ;

sunOb.k = 9;
System.out.println(“ Sum of i,j and k in subOb :”) ;







Output –

Recommended Post   Overloading Constructors

Contents of superOb :

i and j : 10 20


Contents of subOb :

i and j : 7 8

k : 9


Sum of i, j and k in subOb :

i+j+k : 24





Please enter your comment!
Please enter your name here