Tuesday, April 9, 2013

Advantages and Disadvantages of Inheritance in Java


What is the use of Inheritance in Java? Examples where you used the concept of Inheritance in your project?


Inheritance: Code reuse using subclass and super class relationship. Subclass inherits all the members (fields, methods, and nested classes) from its superclass.
Inheritance is unidirectional, it is expressed using  is a “ relationship. The car is a Vehicle, but all the vehicles are not a car.

Example:
 Benefits:
             
Minimize the amount of duplicate code in an application

If  duplicate code (variable and methods) exists in two related classes, we can refactored that hierarchy by moving that common code up to the common superclass.

Better organization of code

Moving of common code to superclass results in better organization of code.

Code more flexible change

Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably. If the return type of a method is superclass.

Where to use inheritance:
  
Before using inheritance first compare the relationship for the two classes. Use inheritance only if there is a parent child relationship is there.
A way to test the relationship is to ask a "is-a" question.

Real time example:

Consider the above example. Here if you ask ‘is a’ question between house and building. House “is a” building , but house is not a bathroom. So here we have a parent -> child relationship between building and house.

Disadvantage:

The inheritance relationship is a, tightly coupled relationship , there will be tight bonding between parent and child. If we change code of parent class it will get affects to the all the child classes which is inheriting the parent code.

Examples from projects:

If you took an example from banking. All the account will have balance amount enquire,withdraw and deposit amount.
So here we can create a parent class Account with
public class Account {

   private double balance;

   public Account(double startingBalance)
   {

getBalance () {…}
debitCash(double amount) {}           
creditCash(double amount){}
}

public class OverdraftAccount extends Account {

   public OverdraftAccount(double balance)
   {
     super(balance);
   }
 }

/* Note:  Constructors of super class are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass using ‘super’ keyword.(As the first line of the subclass constructor) */

this.overdraftLimit = limit;
     this.overdraftFee = overdraftFee;
                       
   public double getAvailableFunds()
   {
     return super.getBalance() + overdraftLimit;
   }
 }

1 comment: