Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic Binding java test

Doing this java exercise I can’t figure out why the last line print out "5".

public class Customer { }

public class RegisteredCustomer extends Customer{}

public class Shop {
    public int computeDiscount(Customer c){return 0;}
}

public class OnlineShop extends Shop {
    public int computeDiscount(Customer c){return 5;}
    public int computeDiscount(RegisteredCustomer c){return 15;}
}


public class OnlinePremiumShop extends OnlineShop{
    public int computeDiscount(RegisteredCustomer c){return 20+super.computeDiscount(c);}
}


public static void main(String[] args) {
        RegisteredCustomer c3 = new RegisteredCustomer();
        Shop s2 = new OnlinePremiumShop();
        System.out.println(s2.computeDiscount(c3));
}

Why java catch the method with Customer parameter, if c3 is both dynamic and static type RegisteredCustomer? I think I’m getting confused by binding..what’s the process of thinking to not get wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Shop s2 = new OnlinePremiumShop();

Here you create an OnlinePremiumShop object and assign it to a reference of type Shop. In Shop, the only method declared is:

    public int computeDiscount(Customer c){return 0;}

So when you call s2.computeDiscount(), you MUST call the one that takes a Customer parameter. Since the concrete type OnlinePremiumShop overrides this method, that is the one that is called and the result is 5.

s2 doesn’t know about any version of computeDsicount() that takes a RegisteredCustomer parameter, so it is unable to bind to that version in the child class.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading