Interface Variables
In this tutorial, we are going to discuss interface variables in java. Every interface variable is always public, static, final whether we are declaring or not.
If any variable in an interface is defined without public, static, and final keywords, the compiler automatically adds the same.
E.g
interface Interf {
int x = 10;
}
public: To make this variable available for every implementation class.
static: Without existing object also implementation class can access this variable.
final:Implementation class can access this variable but cannot modify.
Hence inside interface the following declaration are valid and equal.
int x = 10;
public int x = 10;
public static int x = 10;
public static final int x = 10;
public static int x = 10;
final int x = 10;
public final int x = 10;
static final int x = 10;
As interface variables are public, static and final we cannot declare with following modifiers
- private
- protected
- <default>
- transient
- volatile
Inside implementation classes we can access interface variables but we can’t modify their values.
interface Interf {
int x = 10;
}
class Test implements Interf {
public static void main(String args[]) {
x = 888; //C.E
System.out.println(x);
}
}
That’s all about Interface Variables in Java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!