Reputation: 15960
When I was analysing a code in my project, I came accross this situation. I have got an Interface with complete String constants declaration as below
public interface SampleInterface {
String EXAMPLE_ONE = "exampleOne";
String USER_ID = "userId";
public void setValue();
}
If any class implements this SampleInterface
interface, what happens to the variables it declares?
Also, what is the best strategy:
Upvotes: 16
Views: 14578
Reputation: 22673
In an interface in Java, all members are implicitly public
, and fields in particular are implicitly public static final
. You DON'T have a choice. If you try to use any other permission level than public, the compiler would scream at you as it wouldn't make any sense.
So any implementing class will indeed inherit the members, including these static constant fields.
There are several reasons why you would do this in an interface, and usually it is to use it as a constant store. This idiom is used to simply bundle constants together in one place, not necessarily to have the interface used as part of an inheritance tree in an OO way.
So you can call as usuall MyInterface.MY_CONST
to access one of your constants.
You would do this over an interface usually when you don't need any behavior to be defined, so when you don't need any methods. It's really just a static store (often, the interface is made final
itself as well). You could use an abstract class
for this as well, for instance if you want to encapsulate and hide details of an implementation. But in this case, where you have both fields and methods, usually your objective is simply to provide some constants and a contract for sub-classes.
Considering in your case there's also a method signature as part of your interface, there's obviously an intent to implement this interface. In which case you can still access your data as either:
MyInterface.MY_CONST
,MyExtendingClass.MY_CONST
,instanceOfMyExtendingClass.MY_CONST
.For more information, have a look at:
Upvotes: 34