emmet4u
emmet4u

Reputation: 21

If a class extends another class, can the extended class be initialized rather than extending it?

If a class extends another class, can the extended class be initialized rather than extending it?

Example 1:

public class FoodListAdapter extends BaseAdapter{
    //rest of the codes in here
}

Example 2:

public class FoodListAdapter {
    private BaseAdapter fAdapter;
    //rest of the codes here
}

Can Example2 give a similar result as that of Example1?

Upvotes: 1

Views: 82

Answers (2)

UserF40
UserF40

Reputation: 3611

Example 1 is Inheritance.

Example 2 is Aggregation, a directional one way association representing a Has-A relationship.

Example 1 is more brittle as it directly exposes users to the underlying BaseAdapter class. Example 2 can encapsulate and delegate calls to BaseAdapter. If one day you decide to remove BaseAdapter, users of the FoodListAdapter class never have to know.

Upvotes: 1

galusben
galusben

Reputation: 6402

Both strategies are good. It depends on what you are trying to achieve.

The first example is inheritance, while the second is delegation.

Both are well known design patterns.

https://en.m.wikipedia.org/wiki/Delegation_pattern

Upvotes: 1

Related Questions