What are some alternatives to inheritance?

Showing Answers 1 - 10 of 10 Answers

kavitha

  • Jun 8th, 2006
 

Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

  Was this answer useful?  Yes

‘Is a’ relationship is expressed using inheritance and ‘has a’ relationship by composition/delegation.

eg. Building is a house. hence house extends building
eg. house has a bathroom, hence
class House{
Bathroom room = new Bathroom();

//more code
}

Inheritence and object composition are 2 techniquies for code reuse.

  Was this answer useful?  Yes

dkjena4u

  • Sep 7th, 2010
 

Delegation is an alternative to inheritance in Java. Kavita has provided useful information, but a peice of code snippet could have been more useful.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions