Interfaces define contracts for classes to follow and are often associated with method declarations. They also contain constants known as “interface constants“.

This article will discuss interface constants and how they contribute to creating more maintainable and flexible code.

What is an interface constant?

An interface that contains constants such as static and final fields with values that cannot be changed is known as an interface constants. They are implicitly public, static, and final, regardless of whether these modifiers are explicitly specified.

The purpose of defining constants in an interface is to provide a way to share common values across classes in a clean and organized manner.

Following is the example of defining interface constants

interface Constants {
    int MAX_VALUE = 100;
    String DEFAULT_NAME = "John Doe";
}

class ExampleClass {
    public static void main(String[] args) {
        int maxValue = Constants.MAX_VALUE;
        String defaultName = Constants.DEFAULT_NAME;
        
        System.out.println("Max Value: " + maxValue);
        System.out.println("Default Name: " + defaultName);
    }
}

Interface constants are used to define Shared Values, API definitions, Configuration values, and Enums. Using interface constants, we can achieve code readability and code maintenance.

Categorized in:

Tagged in: