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

For the first question, the "super" call says "run the method defined in the superclass", so it calls Dog.act(), which prints "run" and calls "eat()". When it calls eat(), however, it calls the local version of eat(), the one defined in Underdog, which again calls back to the superclass, and then does its local thing. Clear? :)

For your second question, you can just leave that method out of your subclass. If it's undefined in the inheriting class, the compiler just calls the one defined in the superclass. Think of the toString() method - it's defined for every object, because it is defined in Object, so you can always call it. It just doesn't give anything useful unless you override it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.