Interface variables in Java

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.

interface Shape{
	String shapes ="geometrical shape";


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.

interface Shape{
	public static final String shapes ="geometrical shape";


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:

 * Interface variables example

interface Math{
	public static final double	PI = 3.14;
	public static final double ELUERNUMBER  = 2.718;
	public static final double SQRT = 1.41421;

 * Test interface variables
public class Sample {

	public static void main(String[] args) {
		//Calculate area of circle
		int radious =2;
		//call interface constant Math.PI
		double area = Math.PI*radious*radious;
		System.out.println("Area of Circle ="+ area);		



Area of Circle =12.56

Leave a Comment