Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

same final variable declared in two interface and implemented in one class

Tags:

java

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

like image 840
matt_bj_ninja Avatar asked Oct 04 '13 18:10

matt_bj_ninja


2 Answers

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.

like image 77
Sotirios Delimanolis Avatar answered Oct 10 '22 07:10

Sotirios Delimanolis


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.

like image 29
anubhava Avatar answered Oct 10 '22 05:10

anubhava