HD Pg 324, Sec. 11.6.0 - exercises

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

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 »

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: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: HD Pg 324, Sec. 11.6.0 - exercises

Post 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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 32 guests