BIG
DATA

JAVA

INHERITENCE IN JAVA WITH EXAMPLES

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

Inheritance in object-oriented programming is very similar to the way we inherit characteristics from our parents. Characteristics in object-oriented programming terms are attributes and behaviors of a class that is, the data and methods of a class.

Biological inheritance creates a hierarchical classification that enables you to trace your heritage to generations of relatives who have come before you. The same is true in object-oriented programming. A hierarchical relationship develops as classes inherit from other classes within a program. You can trace this relationship to determine the origins of a class.

  • Inheritance is the ability to define a new class that inherits the behaviors (and code) of an existing class.
  • Inheritance allows a class (subclass) to acquire the properties and behavior of another class (superclass).
  • Inheritance gives you the ability of building a new class definition based on existing class definition.
  • It helps to reuse, customize and enhance the existing code. So it helps to write a code accurately and reduce the development time.
Definitions

Inheritance can be defined as the process where one object acquires the properties of another. A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

class Fruit {
    //...
}
class Apple extends Fruit {
    //...
}

In this simple example, class Apple is related to class Fruit by inheritance, because Apple extends Fruit. Here, Fruit is the superclass/base class and Apple is the subclass/child class.



IS-A and HAS-A Relationship

Programmers use the "is a" test to determine if a relationship exists between classes. The "is a" test determines if the child "is a" parent. For example, a graduate student "is a" student. If an "is a" relationship makes sense, then a parent-child relationship exists and the child can inherit from the parent. If an "is a" relationship doesn't make sense, then a parent-child relationship doesn't exist and the child cannot inherit from the parent, as in the case of an automobile and airplane. An apple "is a" car? This is nonsense, so you shouldn't attempt to create such a relationship.

IS-A Relationship:
In object oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example House is a Building. But Building is not a House.
In Java, you can easily identify the IS-A relationship. Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to have IS-A relationship.

HAS-A Relationship:
HAS-A means an instance of one class "has a" reference to an instance of another class or another instance of same class.It is also known as "composition" or "aggregation". For example House is a Building. House has a bathroom. Apple is a fruit. Apple has seeds. Car is a vehicle. Car has a engine.

Example
Let's understand these concepts with example of Car class
isa-relation

class Car {  
    // Methods implementation and class/Instance members  
    private String color;  
    private int mileage;   
          
    public void carInfo(){  
        System.out.println("Car Color= "+color + " Mileage= " + mileage);  
    }  
  
    public void setColor(String color) {  
        this.color = color;  
    }  
  
    public void setMileafe(int mileage) {  
        this.mileage = mileage;  
    }        
}
As shown above Car class has couple of instance variable and few methods. BMW is a specific type of Car which extends Car class means BMW IS-A Car.
class BMW extends Car{  
    //BMW extends Car and thus inherits all methods from Car (except final and static)  
    //BMW can also define all its specific functionality  
    public void BMWDemo(){  
        Engine BMWEngine = new Engine();  
        BMWEngine.start();  
        }  
}
BMW class uses Engine object's start() method via composition. We can say that BMW class HAS-A Engine.
public class Engine {  
  
    public void start(){  
        System.out.println("Engine Started..");  
    }  
      
    public void stop(){  
        System.out.println("Engine Stopped..");  
    }  
}
RelationshipDemo class is making object of BMW class and initialized it. Though BMW class does not have setColor(), setMileage() and carInfo() methods still we can use it due to IS-A relationship of BMW class with Car class.
public class RelationshipDemo {  
      
    public static void main(String[] args) {          
        BMW objectBMW = new BMW();  
        objectBMW.setColor("BLACK");  
        objectBMW.setMileafe(15);  
        objectBMW.carInfo();  
          
        objectBMW.BMWDemo();  
    }   
}
If we run RelationshipDemo class we can see output like below.
Car Color= BLACK Mileage= 15
Engine Started..
Difference between IS-A and HAS-A relationship
  • In OO design, Inheritance is represented by an is-a relationship. While has-a relationship is represented by composition, association or aggregation.
  • IS-A increases the coupling between different objects - Tightly coupled code. Where as HAS-A promotes low coupling between different objects -Loosely coupled code.
  • Advantage of IS-A:- promotes code reuseability, so code redundancy is reduced.
    Advantage of HAS-A:- can work on other class instance variables & methods without inheriting that class.
  • Example: BMW IS-A Car. BMW HAS-A Engine. House IS-A Building, House HAS-A Bathroom.
  • One of the advantages of Object-Oriented programming language is code reuse. There are two ways we can do code reuse either by implementation of inheritance (IS-A relationship), or object composition (HAS-A relationship).


Types of inheritance
Yes! there are different types of inheritance. Lets go through all.

[1] Single Inheritance
single-inheritance When a class extends another only one class then we call it a single inheritance.

[2] Multiple Inheritance
"Multiple Inheritance" refers to the concept of one class extending (Or inherits) more than one base class. The inheritance we learnt earlier had the concept of one base class or parent. The problem with "multiple inheritance" is that the derived class will have to manage the dependency on two base classes. multiple-inheritance Note: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often leads to problems in the hierarchy. This results in unwanted complexity when further extending the class.
Note: Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple Inheritance is supported in C++.

[3] Multilevel Inheritance
multilevel-inheritance Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived class, thereby making this derived class the base class for the new class. As you can see in below flow diagram C is subclass or child class of B and B is a child class of A.

[4] Hierarchical Inheritance
hierarchical-inheritance In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and D inherits the same class A. A is parent class (or base class) of B,C & D.

[5] Hybrid Inheritance
hybrid-inheritance In simple terms you can say that Hybrid inheritance is a combination of Singleand Multiple inheritance. A typical flow diagram would look like below. A hybrid inheritance can be achieved in the java in a same way as multiple inheritance can be!! Using interfaces. yes you heard it right. By using interfaces you can have multiple as well as hybrid inheritance in Java.



Points of Interests
  • Because inheritance exposes details of the parent's implementation to its subclasses, it's often said that 'inheritance breaks encapsulation'.
  • More to come in the future...