Search code examples
javainheritancestatic-methods

Static and non static methods with the same name in parent class and implementing interface


Am not asking about difference between interface and abstract class.

It is working success individually, right?

interface Inter {
    public void fun();
}

abstract class Am {
    public static void fun() {
        System.out.println("Abc");
    }
}

public class Ov extends Am implements Inter {
    public static void main(String[] args) {
        Am.fun();
    }
}

Why is it getting a conflict?


Solution

  • A static and non static method can't have the same signature in the same class. This is because you can access both a static and non static method using a reference and the compiler will not be able to decide whether you mean to call the static method or the non static method.

    Consider the following code for example :

    Ov ov = new Ov();
    ov.fun(); //compiler doesn't know whether to call the static or the non static fun method.
    

    The reason why Java may allow a static method to be called using a reference is to allow developers to change a static method to a non static method seamlessly.