CMSC
CMSC

Reputation: 157

Polymorphism and Dynamic Binding

Assuming that we have three classes as below

public class Woo extends Zoo {
    public String one() {
        return "wee" + this.two();
    }
    public String extra() {
        return "eek" + this.one();
    }
}

public class Zoo {
    public String one() {
        return "zee";
    }
public String two() {
        return "zow";
    }
}

public class Yoo extends Woo {
    public String two() {
        return "yow";
    }
}

And assuming we made the variable declaration of:

 Zoo z = new Yoo();

What would the output of

System.out.println(z.one() + " " + z.two() + " " + z.extra()); 

be?

My compiler won't let me compile saying that

no method in Zoo has extra

But I thought that since the actual type of z is class Yoo, and since Yoo inherits all the methods from Zoo and Woo class, z.extra() would work....?

Upvotes: 1

Views: 494

Answers (2)

karfau
karfau

Reputation: 668

If you fix the type of z to be Yoo or cast to Yoo before calling extra (as the other answers describe pretty well), you will be able to compile and the output should be

weeyow yow eekzee

Upvotes: 0

jfdoming
jfdoming

Reputation: 975

Even though you assign z a value of type Yoo, it is still a Zoo object. Therefore, Java has no way of knowing about the extra method. You have to cast z to Yoo or Woo to access that method. For example:

Zoo zoo = new Yoo();
Yoo yoo = (Yoo) zoo;

yoo.extra();

Or...

Zoo zoo = new Yoo();
Woo wyoo = (Woo) zoo;

wyoo.extra();

You could even do

Zoo zoo = new Yoo();
((Woo) zoo).extra();

and leave out a line.


In addition, say you were to override extra in your Yoo class. Calling wyoo.extra() from the second example above would call the overridden version from the Yoo class, because Java doesn't care about the contents of a method, just that the method is guaranteed to exist.

Upvotes: 2

Related Questions