偶然发现一个现象:
package org.example;
public class A {
public int prop = 1;
protected void method() {
}
}
package org.example;
public class B extends A {
public int prop = 2;
@Override
protected void method() {
super.prop = 3;
}
}
package org.example;
public class App {
public static void main( String[] args ) {
A a = new B() {
@Override
protected void method() {
super.prop = 3;
}
};
a.method();
System.out.println(a.prop);
A a2 = new B();
a2.method();
System.out.println(a2.prop);
}
}
输出
1
3
本来以为第一次输出的也应该是3,调试后发现 super 对应的类已经不是 A 了
package org.example;
public class App {
public static void main( String[] args ) {
A a = new B() {
@Override
protected void method() {
System.out.println(this.getClass());
System.out.println(super.getClass());
System.out.println();
System.out.println(this.getClass().getSuperclass());
System.out.println(super.getClass().getSuperclass());
System.out.println();
System.out.println(this.getClass().getSuperclass().getSuperclass());
System.out.println(super.getClass().getSuperclass().getSuperclass());
}
};
a.method();
}
}
class org.example.App$1
class org.example.App$1class org.example.B
class org.example.Bclass org.example.A
class org.example.A