Thursday, March 12, 2009

What is the differences between inheritance and composition? (CoreJava)

Question :What is the differences between inheritance and composition? (CoreJava)
Answer :Answer Inheritance:
Inheritance is the ability to derive one class from another; the derived class
(also called the subclass) inherits all
of the methods and data members of its superclass.
class Fruit {
//...
}
class Apple extends Fruit {
//...
}
In the above example, class Apple is related to class Fruit by inheritance,
because Apple extends Fruit. In this
example Fruit is superclass and Apple is subclass.
Composition:
Composition (called "has-a") is a relationship between classes where one
class has a data member that is an instance of
the other class.
class Fruit {
//...
}
class Apple {
private Fruit fruit = new Fruit();
//...
}
In the example above, class Apple is related to class Fruit by composition,
because Apple has an instance variable that
holds a reference to Fruit object.
In this example, Apple is what I will call front-end class and Fruit is what I
will call back-end class.
In a composition relationship, the front-end class holds a reference in one
of its instance variables to a back-end class.

No comments: