Login with  Log in with facebook
Hiring Manager? SIGN UP HERE
2

Explain"is a" and "has a " relationship between classes. Can you explain with a use case. Which one do you prefer and why?

Uthra Natarajan
09/09/2011 at 23:13
1 Answer
1
0

"is a" - Inheritance.

Base class - Fruit

Child class - Apple extends Fruit

 

"has a" - Composition

Class1 - Fruit

Class2 - Apple {

private Fruit fruit = new Fruit();

}

Apple has a Fruit.

 

I prefer composition to inheritance.

While designing objects I find composition to be a better choice from the perspective of testability. The reason being, I can mock parts of the composition structure if I need to, while running unit tests. This is not possible if I have an inheritance hierarchy.

 

Uthra Natarajan
09/09/2011 at 23:14

If you want to post any answer to this forum then you need to log in.
Schedule a Demo

Schedule a Demo with us

Name *
Email *
Phone *
Company *
Details