Thursday, September 15, 2011

JAVA : Read IS-A and HAS-A relationship concept




IS-A

In OO, the concept of IS-A is based on class inheritance or interface
implementation. IS-A is a way of saying, "this thing is a type of that thing." For
example, a Mustang is a type of horse, so in OO terms we can say, "Mustang IS-A
Horse." Subaru IS-A Car. Broccoli IS-A Vegetable (not a very fun one, but it still
counts). You express the IS-A relationship in Java through the keywords extends
(for class inheritance) and implements (for interface implementation).

public class Car {
}
public class Subaru extends Car {
}

HAS-A

HAS-A relationships are based on usage, rather than inheritance. In other words,
class A HAS-A B if code in class A has a reference to an instance of class B. For
example, you can say the following,
A Horse IS-A Animal. A Horse HAS-A Halter.

The code might look like this:

public class Animal { }

public class Horse extends Animal {

    private Halter myHalter;
}

No comments:

Post a Comment