Is there any special scenario that we have to define a constant in interface. If so explain with some examples.
-
There are no scenarios where you have to define a variable in an interface. There are few scenarios where you are able too. – shmosel Jun 21 '16 at 04:01
-
@shmosel Can you tell me where we are able to define variable in interface and what is the purpose of have that? – CrazyJavaLearner Jun 21 '16 at 04:02
-
Please put some research into your question first, and use that to expound on your question. Answers are most helpful when they do more than just restate the first results on Google. – 4castle Jun 21 '16 at 04:05
-
Interfaces can declare constants that will be "inherited" in implementing classes. But it's a practice that's generally [frowned upon](http://stackoverflow.com/questions/320588/interfaces-with-static-fields-in-java-for-sharing-constants) and rendered obsolete by static imports. – shmosel Jun 21 '16 at 04:08
3 Answers
If you want to use some of the variables as constants then you can declare them in interface, as they are inherently public static and final therefore can be accessed as Constants.

- 101
- 4
You can't have variables in interfaces. You can only have constants declared in interfaces.
It is very important to put related stuff together, in the same file or in the same package. This way, you can easily find your code. The only situation that I can think of to declare constants in interfaces is that you put constants that are related to the interface in the interface.
For example, a Rotatable
interface looks like this:
public interface Rotatable {
void rotate(int direction);
int CLOCKWISE = 1;
int ANTI_CLOCKWISE = -1;
}
When the rotate
method is called, either CLOCKWISE
or ANTI_CLOCKWISE
will be passed.
However, why bother? Just use an enum! (unless you're doing android and enums affect performance)
So yeah, there isn't much use of constants in interfaces...

- 213,210
- 22
- 193
- 313
-
You included the unnecessary `static final` but forgot the very necessary `int`. :) – shmosel Jun 21 '16 at 07:25
-
@shmosel Oh yes! Maybe I'm using Swift too much, where types are inferred :) – Sweeper Jun 21 '16 at 07:41
All Constants which are common across all classes implementing this interface should be declared in interface. Also, note that all Constants you declare here are public static and final. Example, Constants for an application are maintained in a common interface.

- 63
- 5
-
*All variables which are common across all classes implementing this interface should be declared in interface.* Is that a fact? – shmosel Jun 21 '16 at 04:03
-