Tutorial :different ways to define a method in an interface



Question:

Is there any difference between:

interface A{      public a();  }  

and

interface A{      abstract a();  }  

and

interface A{      a();  }  


Solution:1

public and abstract are superfluous on interface methods so the three are identical.

Personally I always use the third one.


Solution:2

From section 9.4 of the Java Language Specification:

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

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


Solution:3

Personally I prefer to explicitly declare my interface methods public. Although it is superfluous, in other contexts a method without a modifier is package-private, so I find it can be confusing, especially in interfaces with a lot of static final fields, to imply public in some contexts and package-private in others, when it may not be immediately obvious that you are looking at an interface if you drill to the method from your IDE and don't see the top of the declaration

But I find abstract is superfluous, since the method decalration ends with a semi-colon.

But these are all matters of style and preference. The functionality is exactly the same.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »