Open ZhangAnli opened 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
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!
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
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");
}
}
Look recitation 02 question1. There's also supplementary materials from that recitations for more explanations.
I think this is a general framework for these type of questions, e.g. x.foo(y)
x
and y
.
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):