Search code examples
javastaticprivateoverridingaccess-specifier

static and private method behavior when calling direct on object of child class sounds like overriding?


public class B extends A{

    public static void main(String[] args) {
    new B().privateMethod();//no error -output B-privateMethod.Sounds like overriding
    new B().staticMethod(); //no error -output B-StaticMethod.Sounds like overriding
    }

    private void privateMethod() {
        System.out.println("B-privateMethod.");
    }
    static void staticMethod() {
        System.out.println("B-StaticMethod.");
    }
}


class A{
    private void privateMethod() {
        System.out.println("A-privateMethod.");
    }
    static void staticMethod() {
        System.out.println("A-StaticMethod.");
    }
}

On R&D I found in case of privateMethod()- since this method was not available on object of child class so child class's and parent class's privateMethod() are separate method and they have no relationship so this is not overriding. but in case of staticMethod()- parent class's method was available on object of child class ,and when we define this in child class, object of child class start pointing to child class method.this looks like method overriding but not,since static method does not override.

how does static method handle by java developement kit?


Solution

  • Polymorphism is not for static methods. Static methods are called with JVM instructions invokestatic, whereas polymorphism is achieved with invokevirtual. The calls to static methods are determined at compile time, and polymorphic methods are dynamically dispatched at runtime.

    You can easily tweak your code so that A.staticMethod() is called, by just assigning new B() to a variable of type A.

    public static void main(String[] args) {
        new B().privateMethod();
        A b = new B(); // change here.
        b.staticMethod(); // A.staticMethod() is called here. 
    }