0

在子类的对象上,超类的静态方法是可用的,但是当我们在子类中定义相同的方法时,现在子类的对象开始指向子类的方法。这听起来像是覆盖但它不是,因为静态方法可以'覆盖。这是怎么发生的,java的这个功能叫什么?

class A extends B {
    public static void main(String[] args) {
        new A().method();//call class B's method if method     is not in A otherwise A's
    }

    /*
    public static void method(){
    System.out.println("class A method");
    */
}

class B {
    public static void method() {
        System.out.println("class B method");
    }
}

这似乎是压倒一切的,但不是。jdk 如何管理它?由于我的垃圾平板电脑,我很抱歉。

4

1 回答 1

2

由于Aextends BA(您通过调用创建new A())的实例将具有所有方法,这些方法B具有。因此,如果调用.method()的实例A,VMmethod()会在其自身范围内查找第一个,即 中的动态方法A,然后是 中的动态方法,然后B是 中的静态方法A,最后是 中的静态方法B。这是可能的,因为 VM 允许通过this引用访问静态方法,尽管不鼓励这样做,因为它会损害可读性。

于 2015-04-18T20:58:33.297 回答