static method behaving like other method those can override

不打扰是莪最后的温柔 提交于 2019-12-20 06:37:12

问题


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

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


回答1:


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.



来源:https://stackoverflow.com/questions/29722682/static-method-behaving-like-other-method-those-can-override

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!