Specification states that interface is intended to define the contract for what a class can do and contains a set of methods required to implement. But at the same time, interface may have constants.
For what purpose it is allowed in Java?
What is the point of existence of constants in interface and how can they be used in it? As I understand they can only be taken as arguments by methods. But I do not see much point because interface doesn't say anything about how a class will implement its methods.
Constant variables in Java contain a pointer that points to an immutable location. This means the variable's pointer will not change its location. However, the object referenced through that pointer can be changed. This means the value of the reference object is mutable.
In the Java programming language, the constant interface pattern describes the use of an interface solely to define constants, and having classes implement that interface in order to achieve convenient syntactic access to those constants.
Constants are basically variables whose value can't change. In C/C++, the keyword const is used to declare these constant variables. In Java, you use the keyword final .
We declare constants because we will always need some "magic numbers" that are fixed in the code. Using constants means that they are easier to spot, and that when you change them you will change all of them with a edit.
A constant is part of an interface, too. Constant values are used in design to avoid Magic Numbers, i.e. numbers which have a certain meaning to the implementation, but seem to pop out of nowhere.
There are many cases where numerical values influence the behavior of the code. Consider, for example, an interface for a GUI button. How this button is actually drawn is up to the implementation; but what kind of button it is is part of the contract which forms the interface: Is it a normal push button, has it an image, or is it a checkbox? This behavior can be modified using constants, commonly used by OR'ing values: For example, int buttonType = PUSHBUTTON|IMAGEBUTTON
.
The constants can be used outside the interface.
For example, they can be used by the classes that implement the interface. This may be useful if a single definition is required across implementation classes.
For example, consider an interface that defines some bitwise-OR style constants that may be used consistently across all the subclasses. Only a single definition of these is required, and only a single set need be learned.
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