ABOUT INHERITANCE

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 implementskeywords are used to describe inheritance in Java.
Inheritance in Java
Let us see how extend keyword is used to achieve Inheritance.
class Vehicle. 
{
  ......  
}
class Car extends Vehicle 
{
 .......   //extends the property of vehicle class.
}
Now based on above example. In OOPs term we can say that,
  • Vehicle is super class of Car.
  • Car is sub class of Vehicle.
  • Car IS-A Vehicle.

Purpose of Inheritance

  1. To promote code reuse.
  2. 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 
    }
}
Output :
Child method
Parent method

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
types of inheritance in java

Note: Multiple inheritance is not supported in java through class.

multiple inheritance in java
When a class extends multiple classes i.e. known as multiple inheritance. For Example:

No comments:

Post a Comment