Search code examples
inheritancemethodsstaticoverridingnon-static

Is "Indirect Overriding" of static methods possible in Java?


We can't override a static method (at least in Java).

If I want to override an inherited static method, can I do it via a nested call to a non-static method of the parent class which I have overriden?

class A {
.
.
static func(args) {..M(args)..}
.
.
<Type> M(args) {...}
.
.
}

class B extends A {
.
.
@Override
<Type> M(args) {...}
.
.
}

Or, will this code be able to change the functionality of func?


Solution

  • This is where it breaks:

    I have defined the static method of A with the help of a nested call to M.

    You can’t call a non-static method from a static method.

    If I understand you correctly, you wanted to do something like:

    public class A {
        public static void staticMethod() {
            m();
        }
        public void m() {
            // do something here or leave it to the subclasses
        }
    }
    

    In my Eclipse, at the call to m() I get

    Cannot make a static reference to the non-static method m() from the type A

    To call a non-static method you need an instance to call it on. For example, to ask a person’s name you first need a person object, or the question won’t make sense. In a static context you haven’t got any instance.

    Of course, if you can set up a situation where inside staticMethod you have got an instance of either B or C, you’re there. Then you can just call myInstanceOfBOrC.m().

    The usual solution to what I think you were after is to make an instance of either B or C from the outset and not declare the method static. Then use usual overriding. It may feel like a waste to create an instance for this purpose alone; but it works.