James Nguyen
James Nguyen

Reputation: 13

Java polymorphism: Why is an error returned?

Why does running

Larry var3 = new Jerry();
var3.method3();

output an error instead of

larry 1

harry 1

mary 3

I think it might have something to do with the way the object was created. But it's just my speculation.

This is the code:

public class Harry {
    public void method1() {
        System.out.println("harry 1");
    }

    public void method2() {
        method1();
        System.out.println("harry 2");
    }
}

public class Larry extends Harry {
    public void method1() {
        System.out.println("larry 1");
        super.method1();
    }
}

public class Mary extends Larry {
    public void method2() {
        System.out.println("mary 2");
    }

    public void method3() {
        super.method1();
        System.out.println("mary 3");
    }
}

public class Jerry extends Mary {
    public void method2() {
        super.method2();
        System.out.println("jerry 2");
    }
}

Upvotes: 1

Views: 68

Answers (2)

crimaniak
crimaniak

Reputation: 123

Larry var3 = new Jerry(); // casting Jerry to Larry. 
var3.method3(); // there is no Larry.method3 method.
// You need downcast object to derived class with method3() defined to call it

Upvotes: 0

foxx1337
foxx1337

Reputation: 2046

Use

((Mary) var3).method3();

and it will work fine.

Upvotes: 1

Related Questions