简体   繁体   中英

Why interface methods can't be static in class that implements the interface?

Lets suppose I have code like this:

public interface JustAnInterface {
    void doSomething();
}

public class JustAnInterfaceImplementation implements JustAnInterface {

    @Override
    public static void doSomething() {

    }
}

Why does static doSomething() method shows the error " Method does not override method from its superclass "?

One could say: because @Override and static simply do not go together.

Keep in mind: polymorphism only works for non-static methods. static means that your method is "attached" to the containing class.

In other words: you know everything about static method invocations at compile time. But the process of determining which overridden method to invoke happens at runtime. These two concepts do not go together in Java.

All what GhostCat says is correct but the @Override annotation is not the direct cause of the compilation error.

Even by removing it, the method is not valid at compile time.

You cannot override or implement a method by adding the static modifier in the derived class as overriding/implementing is valid only for instance methods.
Try without the annotation :

public class JustAnInterfaceImplementation implements JustAnInterface {

    public static void doSomething() {

    }
}

You would have a compilation error more specific than which one with @Override

method does not override or implement a method from a supertype

You should get something like :

overriding method is static

The static and non-static methods have different signatures, and not simply because of the static .

The non-static method is secretly taking an extra parameter - the value of this .

If you're familiar with python, you can see this explicitly:

class SomeClass(object):
  def doSomething(self):
    pass // whatever method body

Here, the self parameter is just a regular parameter: you can invoke the method and pass this parameter yourself.

In Java, it's sort of the same. When you invoke the doSomething method, you implicitly pass one parameter to it, and that becomes this .

However, the static method takes zero parameters. So actually, they aren't override-equivalent, and hence you aren't overriding the method correctly.

The JVM would have to somehow determine that the parameter should be discarded. The language could have been written to allow this, but the designers took the easier route of just disallowing it (because there's no good reason to use it anyway).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM