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:
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings.
Interface is basically a complete abstract class. That means Interface only have deceleration of method not their implementation. So if we don't have any implementation of a method then that means if we create object of that interface and call that method it compile nothing as there is no code to compile.
Interfaces in Java are one of the basic concepts of object-oriented programming that are used quite often alongside classes and abstract classes. An interface represents a reference type, meaning that it is essentially just a specification that a particular class that implements it needs to obey.
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:
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