开发者

Abstract methods in a Java interface

Something I've seen a lot but never thought to question it... In a Java Interface, what is the difference between:

public void myMethod();

and

public abstract void myMethod();

I understand the purp开发者_如何学编程ose of the abstract keyword in a Java class, but what purpose does it serve (if any) in an interface?


Both declarations are completely the same, all interface methods do not have implementation (are abstract) hence the abstract keyword is redundant. In my opinion writing abstract in this case increases verbosity of code.


All method declarations are both public and abstract in an interface. No point specifying it at all.

Only void myMethod(); is really needed here.


From Java Specification:

  • 9.4 Abstract Method Declarations .. .. ..

Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.

Every method declaration in the body of an interface is implicitly public.


Both public and abstract are redundant here. I personally prefer omitting them both because in my opinion they're both just noisy in this case.

Whilst you could of course include them, I think it's perfectly reasonable to assume that anyone reading your code knows that all methods in an interface must be public and abstract - it's a well understood feature.


As already said interface methods ARE public and abstract. It is now discouraged to specify them as public abstract:

For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.

It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.

And for completeness interface fields ARE public static and final...


Though you can declare explicitly , All methods in an interface are implicitly public and abstract. The compiler will complain only if you try to make them non abstract ( by providing the body ) and private.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜