HD Pg 324, Sec. 11.6.0 - exercises

Moderator: admin

zeldalex
Posts: 3
Joined: Sun May 12, 2019 8:32 am
Contact:

Re: HD Pg 324, Sec. 11.6.0 - exercises

Post by zeldalex » Wed May 29, 2019 9:10 pm

What I don't undestand is why p.getCalories() will always look at the superClass even if I had declared p as an ApplePie.
The following code at main will never touch the static method at ApplePie:

Code: Select all

 public class TestClass{
    public static void main(String[] args){
        ApplePie ap = new ApplePie();
        Nutritionist n = new Nutritionist();
        n.printCalories(ap); //invoke Pie's static method and print 100
    }
}
Casting at main method gives no difference.

Code: Select all

public class TestClass{
    public static void main(String[] args){
        Pie ap = new ApplePie();
        Nutritionist n = new Nutritionist();
        n.printCalories((ApplePie)ap); //invoke Pie's static method and print 100
    }
}
Whatever I passed to the Nutritionist is treated as a Pie class, and I don't know how to let the Nutritionist invoke the correct subClass. Casting is not a good solution as everytime I have a new type of Pie, I need to modify the Nutrionist class.

Can you give some tips to solve the issue?

admin
Site Admin
Posts: 8702
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: HD Pg 324, Sec. 11.6.0 - exercises

Post by admin » Wed May 29, 2019 11:02 pm

That is how static methods work. They are not polymorphic. They are bound at compile time and not run time. That is why the method to be invoked is decided by the compiler at compile time based on the type of the reference using which the method is invoked. This is explained in the book.

No, I can't give you the solution because there is no one solution. This is something you need to discuss with your trainer or teacher.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests