Let's look at two class hierarchies, a family member and its friends. A family member's hierarchy is kind of fixed over time. It includes a husband, wife, and kids. However, friends get added at some point of time in their life. A wife may suddenly meet her college friend after many years, or a husband comes across his childhood buddy after a span of many years. Let's have a look at the pictorial representation of this:
The question is how do we know who is greeting whom, for example, a friend of the husband will be somewhat formal in greeting the wife. On the other hand, the same friend can go back slapping the husband, as they are old buddies. To resolve this, we need to know both the concrete instances of FamilyMember
and Friend
. Here is a first cut, using instanceof
:
if (friend instanceof HusbandsFriend && familyMember instanceof Wife) { System.out.println("How do you do, Mr. " + friend.getName()); } else...