Interface variables in Java

(Last Updated On: March 5, 2019)

Learn Interface variables in Java with example and Uses.

You know that an interface can contains methods in java, similarly, an interface can contains variables like int, float and string too. In an interface, variables are static and final by default. All variables in an interface in java should have only public access modifier.

For example,

here is a string variable “shapes” declared in the interface.

 

Note that if we don’t write public, static and final before interface variable, the compiler by default understand it as below. However, for readability purpose, it is better to write public static and final before variables in java applications.

 

Real Time Use of Interface

Typically, we keep collections of constants in an interface in java application. FYI, in a large real time project, we had created tons of interfaces containing variables only as a collections of constants. Here, I have written, one of the pseudo interface that contains only constants.

Example of Interface variables in Java

You can see the below example, in which collection of constants related to mathematics are there in interface Math.

In an interface, variables are treated as static and final by default. But, for readability purpose in the project, we write complete declaration e.g. public static final double PI = 3.14;

Java Code:

 

Output:
Area of Circle =12.56