Search code examples
javapolymorphismdynamic-binding

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?


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.