Share This Topic -

Inheritance in java with Examples:

What is a Inheritance ?

The derivation of one class from another class is called Inheritance.

Type of inheritance :

A class that is inherited is called a super class.

The class that does the inheriting is called as subclass.

In above figure all class A is super class.

A subclass inherits all instance variables and methods from its super class and also has its own variables and methods.

One can inherit the class using keyword extends.

Syntax :

Class subclass-name extends super class-name


            // body of class.


In java, a class has only one super class.

Java does not support Multiple Inheritance.

One can create a hierarchy of inheritance in which a subclass becomes a super class of another subclass.

However, no class can be a super class of itself. 

EX :

 class A   //superclass
	int num1;    //member of superclass
	int num2;    //member of superclass
	void setVal(int no1, int no2)   //method of superclass
		num1 = no1;
		num2 = no2;

class B extends A   //subclass B 
	int multi;   //member of subclass
	void mul()   //method of subclass
		multi = num1*num2;   //accessing member of superclass from subclass

class inhe2
	public static void main(String args[])
		B subob = new B();
		subob.setVal(5,6);  //calling superclass method throgh subclass object
		System.out.println("Multiplication is  " + subob.multi);

Output :
Multiplication is  30
Note : Private members of super class is not accessible in subclass,
           super class is also called parent class or base class,
           subclass is also called child class or derived class.