Java – override – parameter difference
public class A{
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 in my past exam
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 is the following output I was right in answer 1 But I don't fully understand why
Because the inner class of B object is (a, a) Do I correctly believe that it cannot override super method m because it is (a, b)? If the parameters of two methods are exchanged, can it be overwritten?
Since it can neither override nor overload, it does nothing but use method m in class B?
Does the object's inner class apply only to itself? Is it like an alien?
Apologize for all the problems
Thank you in advance
Edit:
From my understanding so far, because the static type is set to B, type B cannot see the anon class If you make it public, you can see it, but you still won't use it
This puzzled me about another problem
public class A{ public static int x = 1; public int m(A a,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 calling A1 M, it passes A2 and B1
In class A, when A. m (B, b) is called It calls dynamic types Is this because it becomes a dynamic type once resolved? So can it use the anon class now?
Solution
Here are a few points:
>Methods in anonymous inner classes are not exposed, so public methods cannot be overridden If you must override non abstract methods, always use @ override. > The (static) type of B1 is B, so additional methods declared in anonymous types are not available Although you can do the following:
B b1 = null; System.out.println(new B(){int m(B a,B b){ return 10; }.m(b1,b1));
or
final B b1 = null; new B() { { System.out.println(this.m(b1,b1)); } int m(B a,B b) { return 10; } };
>The language selects overrides with the most specific parameters (if any) instead of the least specific parameters Corrections were made in the previous example, such as system err. println(“donkey”.tocharArray()); Println (object) will not be called. > Rewriting methods can relax the return type, "covariant return type" (since 1.5) When a parameter in a generic parameter type (such as comparable) in a supertype occurs, the situation is not exactly the same