Page 2 of 2

Re: HD Pg 324, Sec. 11.6.0 - exercises

Posted: Wed May 29, 2019 9:10 pm
by zeldalex
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?

Re: HD Pg 324, Sec. 11.6.0 - exercises

Posted: Wed May 29, 2019 11:02 pm
by admin
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.