Java

Inheritance in Java

Inheritance

Inheritance is a process through which two java classes can establish a relation of parent and child among themselves.
The class which acts a  parent is called as 'Super Class'.
The class which act as a child is called as 'Sub Class'.

Diagrammatically an arrow going from sub class to super class denotes inheritance.
So in simple words
 Inheritance can be considered as a process through which object of a sub class acquires the properties of its super class.

Inheritance in Programs

Java uses keyword extends for inheritance.
If a java class need to extend any other class it uses keyword extends for the same reason.
 
Basic Syntax goes like this.
public class SubClass extends SuperClass
{

}
Let us consider a simple example of inheritance.
 
Class A will act as a super class and it have two methods m1() and m2().
 
A.java


class A 
{
 public void m1()
 {
  System.out.println("m1- A");
 }
 public void m2()
 {
  System.out.println("m2-A");
 }
}

Class B will act as a sub class,it have two methods of its own m3() and m4(). It also have two inherited methods m1() and m2().

B.java



class B  extends A
{
 public void m3()
 {
  System.out.println("m3-B");
 }

 public void m4()
 {
  System.out.println("m4-B");
 }
}
Class Demo can be used to access those classes and  now here we can see that we are only instantiating the class B, but we are able to use the methods of class A which have come down to class B under the process of Inheritance.
 
Demo.java


class Demo 
{
 public static void main(String[] args) 
 {
  B b=new B();

  b.m1();
  b.m2();
  b.m3();
  b.m4();
 }
}

Output

Java do not support Multiple Inheritance.

- Java do not support multiple inheritance, at any given point of time a java class can only extend one super class not more than that.
So at any given point of time in life of a java class it can at-least and at-most have one super class.
 
So what happens to the class when they do not extend any class?
- For example in above instance class A did not extend any other class.

Every Java class is subclass of java.lang.Object

 
So here comes the simple statement  which would clear up this doubt.
 
Every class in java is required to directly or indirectly extends a class called as java.lang.Object.
When a java class do not extend some another java class they get extended to java.lang.Object in their compiled version. Hence every class in Java is sub class of java.lang.Object.

Java support Multi Level Inheritance.

class A
{
}

class B extends A
{
}

class C extends B
{
}
This hierarchy is allowed in java. 
Class C gets all the property of class B and class A.
 

Java do no support Cyclic Inheritance

 

 

 

 

 

Related Posts

language_img
Java

Enum in Java

Jul 3, 2015

language_img
Java

Exception

May 22, 2015

Table Of Contents

;