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?
Here you create an
OnlinePremiumShopobject and assign it to a reference of typeShop. InShop, the only method declared is:So when you call
s2.computeDiscount(), you MUST call the one that takes aCustomerparameter. Since the concrete typeOnlinePremiumShopoverrides this method, that is the one that is called and the result is5.s2doesn't know about any version ofcomputeDsicount()that takes aRegisteredCustomerparameter, so it is unable to bind to that version in the child class.