Composition & Inheritance
Composition
Composition is a technique that prevents code duplication by delegating
functionality to other objects. For example, a Party class could delegate
method calls to a List object to provide functionality for a guest list.
This would allow the Party class to selectively expose methods such
as addGuest() instead of exposing every method in the List interface.
Inheritance
Inheritance is a technique that prevents code duplication by inheriting
functionality from parent objects. For example, a Party class could extend
an ArrayList to provide functionality for a guest list. This would allow
Party
objects to be used in enhanced for-loops or methods that accept a List.
Multiple inheritance is not allowed in order to prevent the ambiguity that arises
when multiple parents implement the same feature independently.
This ambiguity is called The Diamond Problem (or The Deadly Diamond
of Death) due to the shape of the resulting object hierarchy.
Method Overriding vs Method Overloading
Method overriding allows a subclass to change the functionality of a superclass.
This occurs when a subclass defines a non-static method with the same method
signature as a parent method. As of Java 5, the overridden method can declare
either the same return type or a covariant (subclassed) return type.
An overridden method will be invoked even when an object is cast to its
parent’s type.
Method overriding is commonly confused with method overloading. Method
overloading occurs when two or more methods in a class have the same name
with different method signatures. Method overloading provides an API with
flexibility by allowing clients to call up an appropriate version of a method
without having to pass in null values for optional parameters.
|