Consider the following two classes.
public class Dog
{
public void act()
{
System.out.print("run");
eat();
}
public void eat()
{
System.out.print("eat");
}
}
public class UnderDog extends Dog
{
public void act()
{
super.act();
System.out.print("sleep");
}
public void eat()
{
super.eat();
System.out.print("bark");
}
}
Assume that the following declaration appears in a client program.
Dog fido = new UnderDog();
What is printed as a result of the call fido.act() ?
(a) run eat
(b) run eat sleep
(c) run eat sleep bark
(d) run eat bark sleep
(e) Nothing is printed due to infinite recursion
I know this is an application of polymorphism and got the answer correct(D), but can anyone explain the process behind this? (e.g. Upon reaching this line, the compiler will choose... or sth like that)
Also, what do you do/ happens if you are going to extend from a superclass and in the subclass you will just use the method that the superclass provided?
For example, in the above, if eat() in Underdog didn't need the System.out.print("bark") what do you write instead? Is it
public void eat()
{
super.eat();
}
or can I leave it blank or just skip this method all together?
Thank you
Source: CollegeBoard AP Computer Science Sample Question