public class A{
public static int x = 1;
public int m(A a, B b){
return a.m(b, b) + x;
}
}
public class B extends A {
public int m(A a1, B a2){
if(a1 == a2)
return x;
return super.m(a1,a2);
}
}
This is a question from a past exam of a subject I am taking.
public class Main{
public static void main(String[] args){
B b1 = new B(){int m(A a, A b){ return 10; }};
System.out.println(b1.m(b1, b1));
}
}
The question is, what does the following output. I was correct in the answer of 1. But I failed to fully understand why.
Since the inner class of the B object is (A,A). Am i correct in thinking it can not override the super method m since it is (A,B)? Would it be able to override, if the parameters of the two methods were swapped?
Since it can neither override or overload, it does nothing and simply uses the method m in B class?
Does the inner class of the object, only work for itself? Is it like an anon class?
Apologises about all the questions.
Thanks in advance.
Edit:
From my understanding so far, its because the static type is set to B, so the type B is unable to see the anon class. If this was set to public, it would be able to be seen, but it still wouldn't be used.
This confused me on another question.
public class A{
public static int x = 1;
public int m(A a, B b){
return a.m(b, b) + x;
}
}
public class Main{
public static void main(String[] args){
A a1=new A();
A a2=new A(){
int m(A a,B b){
return 10;
}};
B b1=new B();
System.out.println(a1.m(a2,b1));
}
}
When the following is called, the output is 11. When a1.m is called, it passes a2 and b1.
In the A class, when a.m(b,b) is called. It calls the dynamic type. Is this because it changes to the dynamic type once parsed? So now it is able to use the anon class?