I was reading this post Why would a static nested interface be used in Java? in particular the first answer. In that answer is written that use the words "public" or "public final" on interface fields are redundant. My question is: why? Why should I remove them? If I have something like this:
public interface Int1 { public void add(); void remove(); }
Doesn't it mean that I want add
method to be implementated by whatever class while remove
method to be implementated only by classes of my same package?
Are “public” and “public final” redundant for interface methods?
Yes.
All methods in an interface are implicitly public
and abstract
(but not final
).
All fields in an interface are implicitly public
, static
and final
.
The JLS states this. It also states that these modifiers can be left out.
Why? Well there are a variety of reasons:
Fields and methods are implicitly public
because the point of an interface is to declare an ... interface that other classes can see. (If you want / need to restrict access, this is done via an access modifier on the interface itself.)
Fields are static
because if they were not you would be declaring visible instance fields on an object ... and that's bad for encapsulation.
Fields are final
because non-final fields would be another way of declaring public
static
fields ... which are terrible from an OO perspective.
Methods are abstract
because allowing method bodies would effectively turn interfaces into abstract classes.
Another reason for making methods abstract and fields static in an interface is that if they didn't, diamond inheritance, and inheritance of a method from two distinct interfaces would both be problematic.
But either way, this is how Java is defined, so the questions are moot ... unless you are thinking of inventing your own programming language.
Note that in Java 8, you can declare methods in an interface, using the default
modifier. And in Java 9, you can declare private
methods, in some cases. But use of the public
keyword is still redundant.
Why should I remove them?
You don't have to remove them. The Java compiler doesn't care. You can remove them, but you don't have to remove them, unless you are trying to conform to some Java style guidelines that insist on this. Your code will probably be more readable if you are consistent, but you could make it consistent by using the redundant modifiers everywhere; e.g. adding them rather than removing them.
Doesn't it mean that I want add method be implemented by whatever class while remove method implemented only by classes of my same package?
No it doesn't mean that. Or at least, it might mean that to you, but it won't mean that to the Java compiler, other Java tools ... or other people reading and maintaining your code. IMO, it would be ill-advised to place any meaning on the presence or absence of redundant keywords.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With