Question Set 3.2

3 views
Skip to first unread message

Axat

unread,
Apr 21, 2011, 12:58:13 AM4/21/11
to UBC CPSC 210
The question asks whether the code would execute. The solution
provided states that since eat() has not been declared in the animal
class, which is an apparent type of anAnimal this code would not
execute. But, do we refer to the actual type or the apparent type when
making the method call since eat() is defined in the Dolphin class,
which is an actual type of anAnimal? Also, would this execute if we
had an eat() method in the animal class?

Paul Carter

unread,
Apr 21, 2011, 12:47:27 PM4/21/11
to ubc-cp...@googlegroups.com
Here is the code snippet from the question:

Animal anAnimal = new Dolphin():
anAnimal.eat();

We are told that the eat() method belongs to Dolphin but not Animal.

The apparent type of an object reference determines the class whose members can be invoked. In the example above, the apparent type of anAnimal is Animal and so we can call members of the Animal class. Given that the eat() method doesn't belong to the Animal class, we can not call it. If the Animal class were to have an eat() method, there would be no problem with the code above.

Now let's suppose that the Animal class *does* have an eat() method and that this method is overridden in the Dolphin class. It is the actual type of the object reference that determines which version of the eat() method is called. In the example above, the actual type of anAnimal is Dolphin and so, in this scenario, the second line of code above calls the eat() method in the Dolphin class.

Paul

Reply all
Reply to author
Forward
0 new messages