2

インターフェイスを実装する Java クラスを実装しています。
ポイントは、このクラスのメソッドは静的でなければならないということですが、インターフェイスではメソッドを静的として宣言することはできません (既知のとおり)。クラスで宣言しようとすると、次のエラーが発生します。 static メソッドは InterfaceName からインスタンス メソッドを隠すことはできません。」

このサイトで検索しましたが、解決策は見つかりませんでしたが、インターフェイスを実装する抽象クラスを作成し、クラスで抽象クラスを拡張するという提案がありましたが、機能しません。

なにか提案を?

みんな、どうもありがとう!

4

1 に答える 1

4

The link mvw posted ( Why can't I define a static method in a Java interface? ) describes the reason for not allowing static methods in interfaces and why overriding static methods iis not a good idea (and thus not allowed).

It would be helpful to know in what situation you want to use the static method. If you just want to call a static method of the class, jut give it another name as andy256 suggested. If you want to call it from an object with a reference to the interface, do you really need the method to be static?

To get around the problem, my suggestion is that if you really want to call a static method with the same signature as the interface method, call a private static method:

class MyClass implememts SomeInterface {

    @Override
    public int someMethod(int arg1, int arg2) {
        return staticMethod(arg1, arg2);
    }

    private static int staticMethod(int arg1, int arg2) {
        // TODO: do some useful stuff...
        return arg1 + arg2;
    }
}
于 2013-07-31T12:56:10.737 に答える