In the previous posts you have learned about the Object Oriented Programming(OOP) Principles( you can refer them here ).So,one of the brightest theories of OOP is the inheritance,we can use the information by acquiring from one class to another and in this way we can manage our data in a hierarchial order.

Mainly we can use inheritance in Java by using extends and implements keywords extends use mainly normal single inheritance where as implements is used for multiple inheritance which cannot be implemented directly in Java using extends keyword.

So,in Java we have two relationships in Inheritance.They are :
  1. IS-A relationship.
  2. HAS-A relationship.
  • IS-A relationship : We can explain the inheritance actually like,eg: Dog IS-A Animal , BMW IS-A Car.Here we have a simple example.
class Animal{
}

class Dog extends Animal{
}

class Cat extends Animal{
}

public class Kitten extends Cat{
}
         
Now based on above we can come to these conclusions:

  • Animal is the superclass of Dog and Cat.
  • Dog and Cat are subclasses of Animal.
  • Kitten is the subclass of Cat and Animal.
These conclusions can be mentioned in IS-A form as:
  • Dog IS-A Animal.
  • Cat IS-A Animal.
  • Kitten IS-A Cat.
  • So,we can say that Kitten IS-A Animal.
We can explain this with the help of an example program.

public class Kitten extends Cat{
   public static void main(String args[]){

      Animal a = new Animal();
      Cat c = new Cat();
      Kitten k = new Kitten();

      System.out.println(c instanceof Animal);
      System.out.println(k instanceof Cat);
      System.out.println(k instanceof Animal);
   }
}

Here we can see that Kitten class is creating objects for Animal ,  Cat , Kitten classes.We are testing whether Kitten object is an instance of Animal and Cat by using an instanceof operator.We will get the output as:


true
true
true


So,here we covered the inheritance with extends keyword,we will see implements concept in detail in Interface concept.



  • HAS-A relationship : The HAS-A relationship mainly deals with the usage of a certain code used in one class which is extended from an another class.In other words,if a class Vehicle has a subclass class Car and class B has a variable called myBrake which belongs to Brake class,then we can say Car HAS-A Brake.
This can be explained in the below code:
public class Vehicle { }
public class Car extends Vehicle {
      private Brake myBrake;
}


We can also see examples like:

  • class Room { .... }
  • class Bathroom extends Room{ private Tub myTub; }
So in this we can see Room is a superclass,Bathroom is a subclass which has a Tub instance variable so we can say a Room HAS-A Tub.


So,in this way we can explain the inheritance concepts.The main advantages if Inheritance are Code Reusability and ability to support polymorphism.


In the next posts more and more concepts will be covere,Stay Tuned!!


Au Revoir!!