The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned. In other words, interfaces can declare only constants, not instance variables.
interface variables are public, static, and final by definition; we're not allowed to change their visibility.
No you cannot have non-static variables in an interface. By default, All the members (methods and fields) of an interface are public.
It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public and all fields are public, static, and final by default.
I have a question in my mind, Why can't be a member variable in Interface be a non constant.. The logic of being static stood right in my mind that if one needs to access the variable of Interface then it is must for it to be static as we cannot create the instance of the Interface but Why the need of final arises?? The below code shows how the interface member variables are made static final even though we dont mention it by default....
interface inter{
int a=10; // It becomes final static by default
public void interFunc();
}
class cls implements inter{
public void interFunc(){
System.out.println("In Class Method WITH a's Value as --> "+a);
}
}
class Test{
public static void main(String[] args){
inter in= new cls();
in.interFunc();
}
}
Thanks in advance !!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With