Search code examples
javainterfacestaticfinal

Can an Interface variable be reinitialised?


interface abs{
 int a=10;// by default final static
     void callme(); 
}
class B implements abs{
    int a =11;// reinitializing

    void call()
    {
            System.out.println("No problem"+a);
    }
    public void callme()
    {
            System.out.println("Call me"+a);
    }

}
class main{


    public static void main(String args[]){

        B m=new B();
        m.call();
        m.callme();
    }

}

In Herbert Schildt book, I have read that the interface variables are default Final and static. Which implicitly means that it will act like a constant. but when I am assigning 11 in the variable a in my above mentioned code, it is not giving any error.

o/p No problem11 Call me11


Solution

  • You're not re-initializing the variable, but you're hiding it.

    In order to access abs's a member, you have to refer it with the interface name. Something like:

    System.out.println("No problem" + abs.a);