javastaticoverridingearly-binding

static method behaving like other method those can override


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.


Solution

  • 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.