Variables in Java Interfaces
In java, an interface is a completely abstract class. An interface is a container of abstract methods and static final variables. The interface contains the static final variables. The variables defined in an interface can not be modified by the class that implements the interface, but it may use as it defined in the interface.
🔔 The variable in an interface is public, static, and final by default.
🔔 If any variable in an interface is defined without public, static, and final keywords then, the compiler automatically adds the same.
🔔 No access modifier is allowed except the public for interface variables.
🔔 Every variable of an interface must be initialized in the interface itself.
🔔 The class that implements an interface can not modify the interface variable, but it may use as it defined in the interface.
Let's look at an example code to illustrate variables in an interface.
interface SampleInterface{
int UPPER_LIMIT = 100;
//int LOWER_LIMIT; // Error - must be initialised
}
public class InterfaceVariablesExample implements SampleInterface{
public static void main(String[] args) {
System.out.println("UPPER LIMIT = " + UPPER_LIMIT);
// UPPER_LIMIT = 150; // Can not be modified
}
}
When we run the above program, it produce the following output.
In the next tutorial, we will learn about extending interfaces.