Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member Variables of an interface must be final... Why?

Tags:

People also ask

Why data member is final in interface?

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.

Are all variables in an interface final?

interface variables are public, static, and final by definition; we're not allowed to change their visibility.

CAN interface have non final variables?

No you cannot have non-static variables in an interface. By default, All the members (methods and fields) of an interface are public.

Is data members of an interface are by default final?

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 !!!