静态方法的行为与其他可以覆盖的方法相同 [英] static method behaving like other method those can override

查看:171
本文介绍了静态方法的行为与其他可以覆盖的方法相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在子类的对象上,可以使用超类的静态方法,但是在子类中定义相同的方法的时候,现在子类的对象开始指向子类方法。这个完整听起来像覆盖但是不是,因为静态方法无法覆盖。如何发生这种情况以及java的这个功能是什么?

On object of child class, static methos of super class are available but when we define same method in child class, now object of child class start pointing to child class method.this complete sounds like overriding but it is not,since static method can't override. How this is happen and what this functionality of java is called?

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");
    }
}

这似乎是重写但不是.jd jdk管理它?
由于我的垃圾平板电脑,我很抱歉。

This seems like overriding but not.how jdk manage it? I am sorry for the formet due to my rubbish tablet.

推荐答案

由于 A extends B ,一个 A 的实例(通过调用 new A())将包含所有方法, B 。因此,如果在 A 的实例上调用 .method(),则VM会查找 method()首先在它自己的范围内,即 A 中的动态方法,然后是 B中的dyanmic方法,然后是 A 中的静态方法,最后是 B 中的静态方法。这是可能的,因为VM允许通过引用访问静态方法,但不鼓励这样做,因为它会影响可读性。

Since A extends B, an instance of A (which you create by calling new A()) will have all methods, which B has. Therefore, if you call .method() on an instance of A, the VM looks for a method() first in its own scope, i.e. the dynamic methods within A, then the dyanmic method within B, then the static methods within A and finally the static methods within B. This is possible because the VM allows accessing static methods via a this reference, although this is discouraged since it compromises readability.

这篇关于静态方法的行为与其他可以覆盖的方法相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆