有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中棘手的方法重载

class ABC {
    void doMe(String s) {
        System.out.println("String");
    }
}

class XYZ extends ABC {
    void doMe(Object o) {
        System.out.println("Object");
    }
}

public class StopStart  {
    public static void main(String[] args){
        ABC o = new XYZ();
        o.doMe(null);
    }
}

会发生什么,为什么? 字符串类扩展对象。那么将执行哪个doMe()。 这是编译错误吗


共 (1) 个答案

  1. # 1 楼答案

    重载是在编译时根据变量o的编译时类型解决的。因此,在XYZ子类中定义哪些方法并不重要。只有ABC的方法是相关的

    因此,编译器只考虑void doMe(String s),这就是所选择的方法