Wednesday 13 September 2017

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties of the parent object. When we inherit an existing class, we can reuse methods and fields of a parent class, and we can add new methods and fields also.

Advantages:

  •  For Method Overriding
  •  For Code Reusability


Example:

 class B extends A  
 {  
   //methods and fields  
 } 

The extends keyword is used to inherit the properties of the super class. In Java, a class which is inherited is called the parent or super class and the new class is called child or subclass.

Example using proper Java Code:

class A
 void display()
{
 System.out.print("Hello ");
}
}
class B extends A
{
 System.out.println("world");
 public static void main(String args[ ])
{
 B obj= new B();
 }
}

OUTPUT :

 Hello World

Types of Inheritance:-

  • Single inheritance
  • Multilevel inheritance
  • Hybrid inheritance
  • Hierarchical inheritance
  • Multiple inheritance

Single Inheritance:

Single inheritance is very easy to understand. When a class extends another one class only then we call it a single inheritance.The below diagram shows that class B extends only one class which is A. Here A is a parent class of B and B would be a child class of A.

Multilevel Inheritance:

When a class extends a class, which extends another class then this is called multilevel inheritance. For example, class C extends class B and class B extends class A then this type of inheritance is known as multilevel inheritance.

Hybrid Inheritance:

A hybrid inheritance is a combination of more than one types of inheritance. For example when class A and B extends class C & another class D extends class A then this is a hybrid inheritance because it is a combination of single and hierarchical inheritance.

Hierarchical Inheritance:

When more than one classes inherit the same class then this is called hierarchical inheritance. For example class B, C extend the same class A.

Multiple Inheritance:

When one class extending more than one class then this is called multiple inheritance. For example, class A and B extend the same class C.


Note: Multiple inheritance is not supported in Java through classes.



Hybrid Inheritance









No comments:

Post a Comment