Re: HD Pg 324, Sec. 11.6.0 - exercises
Posted: 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:
Casting at main method gives no difference.
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?
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
}
}
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
}
}
Can you give some tips to solve the issue?