In this section, we will learn what the interface field is and how to use it in Java.
Note: Also, we’re assuming you’re already familiar with interfaces.
What is Field in Java Interface?
So far, we’ve learned there are a couple of types of methods that can be declared inside an interface. These methods are:
Other than methods, we can declare and define member variables inside an interface as well.
Note: These variables are implicitly `public` and `static` and `final`.
This means, because the variable is implicitly `final` we need to set its value right where it’s being declared and after that we cannot change this value anymore.
Also, because these identifiers are static, we need to use the name of the target interface or the name of the class that implemented the target interface in order to invoke the identifiers.
How to Define Field in Java Interface?
To create a field in an interface is the same as the way we do it in classes.
Define the data-type and the name of the variable and then assign its value right where the declaration is happening.
Example: using field in Java Interface
public interface FirstInterface { String name = "FirstInterface"; }
To access this `name` variable, we can either use the name of the interface (FirstInterface in this case) or use the name of the class that implemented the interface.
Example: invoking Java Interface Field
public class SClass implements FirstInterface { } public class Simple { public static void main(String[] args) { System.out.println(SClass.name); System.out.println(FirstInterface.name); } }
Output:
FirstInterface FirstInterface
As you can see via both the name of the class and via the name of the interface, we accessed the static variable and sent its value to the screen.
Java interface field Note:
Again, we emphasize the fact that after initializing such variables, we cannot change its value anywhere in the interface or in the classes that implement the interface. This is because they are implicitly `final`.