nus-cs2030 / 2021-s1

27 stars 48 forks source link

19/20 Sem 2 Q1 - Polymorphism #550

Open ZhangAnli opened 3 years ago

ZhangAnli commented 3 years ago

Description

Hi can anyone explain why the question below has an answer of "1534"? I thought type checking happens during runtime and therefore had an answer "1555". :(

Topic:

Finals

Screenshots (if any):

Screenshot 2020-11-29 at 3 52 36 PM
kohkenneth commented 3 years ago

Hi Anli, I think you can refer to this post for some inspiration! https://github.com/nus-cs2030/2021-s1/issues/544

remuskwan commented 3 years ago

Hi, static binding occurs during method overloading. So the method to be called is decided during compile time. In the case of line 3, ab is of type A during compile time as it is declared to be so, thus the method foo(A a) in class B is called. In line 4, i is of type I during compile time as it is declared to be so, thus the method foo(I i) is called. Hope this helps! Screenshot 2020-11-29 at 5 07 55 PM

KongXinyue commented 3 years ago

b.foo(ab) refers to the method in class B, which takes in a A object b.foo(i)refers to the method in class B, which takes in I

wongzw commented 3 years ago

Hi @ZhangAnli,

b.foo(ab) means that you are calling the method with the input of Type A in Class B -> Printing of 3 b.foo(i) means that you are calling the method with the input of Type I in Class B -> Printing of 4

Below is my code for reference :)

 interface I {
      void foo(A a);
      void foo(I i);
 }

class A implements I{
    public A(){};

    public void foo(A a){
        System.out.println("1");
    }

    public void foo(I i) {
        System.out.println("2");
    }
}

class B extends A implements I{
    public B(){};

    public void foo(A a){
        System.out.println("3");
    }

    public void foo(I i) {
        System.out.println("4");
    }

    public void foo(B b) {
        System.out.println("5");
    }
}
nowknowing commented 3 years ago

Look recitation 02 question1. There's also supplementary materials from that recitations for more explanations.

pikasean commented 3 years ago

I think this is a general framework for these type of questions, e.g. x.foo(y)

  1. Determine compile time type of x and y.
  2. Check overloaded methods.
  3. Check overridden methods.