Monday, March 23, 2009

About inheritance in java.

Inheritance in java – is the inclusion of behavior (i.e. methods) and state (i.e. variables) of a base class in a derived class so
that they are accessible in that derived class. The key benefit of Inheritance is that it provides the formal mechanism for
code reuse. Any shared piece of business logic can be moved from the derived class into the base class as part of
refactoring process to improve maintainability of your code by avoiding code duplication. The existing class is called the
superclass and the derived class is called the subclass. Inheritance can also be defined as the process whereby one
object acquires characteristics from one or more other objects the same way children acquire characteristics from their
parents. There are two types of inheritances:

1. Implementation inheritance (aka class inheritance): You can extend an application’s functionality by reusing
functionality in the parent class by inheriting all or some of the operations already implemented. In Java, you can only
inherit from one superclass. Implementation inheritance promotes reusability but improper use of class inheritance can
cause programming nightmares by breaking encapsulation and making future changes a problem. With implementation
inheritance, the subclass becomes tightly coupled with the superclass. This will make the design fragile because if you
want to change the superclass, you must know all the details of the subclasses to avoid breaking them. So when using
implementation inheritance, make sure that the subclasses depend only on the behavior of the superclass, not on
the actual implementation. For example in the above diagram, the subclasses should only be concerned about the
behavior known as area() but not how it is implemented.

2. Interface inheritance (aka type inheritance): This is also known as subtyping. Interfaces provide a mechanism for
specifying a relationship between otherwise unrelated classes, typically by specifying a set of common methods each
implementing class must contain. Interface inheritance promotes the design concept of program to interfaces not to
implementations. This also reduces the coupling or implementation dependencies between systems. In Java, you can
implement any number of interfaces. This is more flexible than implementation inheritance because it won’t lock you into
specific implementations which make subclasses difficult to maintain. So care should be taken not to break the
implementing classes by modifying the interfaces.
Which one to use? Prefer interface inheritance to implementation inheritance because it promotes the design concept of
coding to an interface and reduces coupling. Interface inheritance can achieve code reuse with the help of object
composition. If you look at Gang of Four (GoF) design patterns, you can see that it favors interface inheritance to
implementation inheritance.

No comments:

Post a Comment

Thanks for your opinion....