Thursday, March 15, 2007

Inheritance Concept

Use of Inheritance

* To promote code reuse
* To use polymorphism

Inheritance in java is done by either extending a class or implementing the interfaces.

Inheritance is all about having a parent child relationship.So instead of rewriting the same functionality several times , you can just inhert those from the parent class.

Inheritance relationship can be of two types.

IS-A Relationship

Has-A Relationship

Is-A relationship is said to be direct relationship and can be done by either extending the parent class or by implementing the interface as said earlier.

For example

class Vehicle{}

class car extends vehicle{}

class ford extends car{}

In this case ford IS-A car . car IS-A Vehicle . So in the class Vehicle we can define several properties and functionalities that are similar , and declare several functionalities as abstract so that they can be overriden by the subclasses that inherit them.Since we have abstract methods in Vehicle class , we need to declare Vehicle as a abstract class.


Has-A relationship is said to be indirect relationship , in the sense , you dont want to extend or implement anything , rather create a instance of the class you want to inherit , and use that instance to invoke its methods.In this way the user dont have to know anything about the inherited class.For him,it seems like the functionality is in his Class.

for example

class Animal{}

class Halter { void tie(Rope r) { } }

class horse extends Animal {
Halter myhalter;
void tie(Rope r) { myhalter.tie(Rope r); }
}

In this case horse IS-A Animal.But Halter is not a Animal.Its just a equipment used to tie the horse. So horse Has-A Halter.Though horse doesnot extend or implement Halter it can use the 'tie' functionality by creating a instance of the Halter class.This is done as shown above.Now it seems like , we are invoking the 'tie' functionality of the horse, which in turn invokes the 'tie' functionality of Halter Class.so the actual implementation goes in Halter class and the user need not be aware of what is happening in the Halter class.For him its the tie method in the horse class is performing the operations.

No comments: