Here's a goo mock SCJP 6.0 exam question on how associations and aggregations are implemented in Java code:
Programatically in Java, how would you express the fact that a cup sometimes has coffee in it?
a) public class Cup extends Coffee{}
b) public class Coffee extends Cup {}
c) public class Cup { Coffee coffee;}
d) public class Coffee { Cup cup; }
Option c) is correct.
The extends keyword expresses an is-a relationship, so Cup extends Coffee would imply that a Cup is Coffee, which doesn't really make sense.
When we declare instance variables within classes, we are expressing a has-a relationship. So, option c), where a cup has an instance of Coffee, would be best expressing the fact that a cup can sometimes contain coffee.
Option a) can be read as a Cup is Coffee
Option b) can be read as a Coffee is a Cup
Option c) can be read as a Cup has Coffee
Option d) can be read as a Coffee has a Cup
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment