Skip to content
Advertisement

Java Inheritance, instanceof, casting – how to accept a children object throught parent object?

JavaScript

I have three classes: (Parent) Animal, (Child) Bird & Monkey

Monkey has weight & two pet Animals, which can be another Monkey, or bird

Bird has weight & a name (weight, name)

Together, they form a TREE, where leaf nodes are Bird, and non-leaf nodes are Monkeys (SEE VISUAL)

JavaScript

While recursively traversing this tree to find a bird with a certain name, i need to check if the curent node is a Bird or Monkey

JavaScript

When I try to do this, it says that

JavaScript

I want to use parent-child inheritance in this problem, but its not allowing me to access the properties of the child object, since im using the parent object declaration in the variable.

How can I solve this problem? I want to use inheritance, but I just can;t figure it out. Please help. I also have some smaller questions in the code below. If anyone can help clarify those, that would be very helpful.

JavaScript

Advertisement

Answer

If you want to avoid casting, you can implement the search polymorphically on the Animal types:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement