有人可以解释编译器/运行时如何在示例中运行适当的方法吗?有 6 个类和一个void m(/* ... */)具有不同参数的方法。我知道编译器会分析声明的类型。输出总是来自中产阶级的“M”。
public class All {}
public class Most extends All {}
public class Special extends Most {}
public class Top {
public void m( All p ) { System.out.println("A"); }
}
public class Middle extends Top {
public void m( All p ) { System.out.println("M"); }
public void m( Special p ) { System.out.println("L"); }
}
public class Bottom extends Middle {
public void m( Most p ) { System.out.println("V"); }
public void m( Special p ) { System.out.println("X"); }
}
public class Main {
public static void main(String[] args) {
All all = new All();
Most most = new Most();
Special special = new Special();
Top x = new Middle();
Top y = new Bottom();
Middle z = new Bottom();
x.m( most ); // Output is M
x.m( special ); // Output is M
y.m( all ); // Output is M
y.m( special ); // Output is M
z.m( all ); // Output is M
z.m( most ); // Output is M
}
}
蝴蝶不菲
相关分类