Hi I have two interface Ainterface and Binterface having same static final variable as 'i' which is declared as 10 and 20 respectively, I am implementing these two interfaces two my class InterfaceCheck where I am declaring same interface variable as static and final and initialized to 30. When I try to print the value of i in my class I am getting 30 as output. can some one explain me why I am able to reinitialize i to some other value even though its a final variable.
CODE
public interface Ainterface {
public final static int i=10;
}
public interface Binterface {
public static final int i=20;
}
public class InterfaceCheck implements Ainterface,Binterface {
public static final int i=30;
public static void main(String[] args) {
System.out.println(i);
}
}
>> output : 30
Class fields are always resolved on the static type of the reference.
In
public static void main(String[] args) {
System.out.println(i);
}
it implicitly does
System.out.println(InterfaceCheck.i);
so that is what you see.
Also, static fields are not inherited.
Static variables belong to the class itself (not to the instance) and these variables are not inherited by child class or implementing class.
Therefore:
public class InterfaceCheck implements Ainterface,Binterface {
public static final int i=30;
}
is not overriding i
from those 2 interfaces. It is actually declaring a new independent static final variable.
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