Danny P. Danny P. - 4 months ago 8
Java Question

anonymous innerclass of interface type accesses 'overrided' fields

Why does an anonymous inner class constructed from an interface return data from the interface when the same data is redefined in the anonymous inner class definition. Please take a look at this code, where it appears that the fields in the interface and the anonymous class, with the same name get accessed:

interface Item{
int data=0;
String text="";
}
public class Problem2{
public static void main(String[] args){
Item item=new Item(){ public int data=2; public String text="an item";
public boolean equals(Object object){
if(object instanceof Item){
Item test=(Item)object; //tests on next line
System.out.println(test); System.out.println(String.format("data: %d; text: \"%s\"", test.data, test.text)); //returns data and text fields of interface, after returning fields defined in anonymous class on toString call
System.out.println(test); //toString returns same
return data==test.data && text.equals(test.text); } return false;}
public String toString(){return String.format("{data: %d; text: \"%s\"}", data, text);} };

System.out.println(((Object)item).equals(item)); //returns false
}
}


Please explain how it returns the field of the interface while the fields of the anonymous inner class does not change.
Output:

{data: 2; text: "an item"}
data: 0; text: ""
{data: 2; text: "an item"}
false

Answer

in java you cannot override variables

you only override methods

and here while creating the anon class when you type test.data it will refer to the interface data not the local variable (local variable accessible using this.data or data directly) since you issued the .data on an object of the interface type.

to resolve you issue just use getter methods

here is full example

interface Item{
    int data=0;
    String text="";
public int getData();
public String getText();

}
public class Test12{
    public static void main(String[] args){
        Item item=new Item(){ public int data=2; public String text="an item";
            public int getData(){
                return data;
            }
            public String getText(){
                return text;
            }
            public boolean equals(Object object){
                if(object instanceof Item){
                    Item test=(Item)object; //tests on next line
                    System.out.println(test); System.out.println(String.format("data: %d; text: \"%s\"", test.getData(), test.getData())); //returns data and text fields of interface, after returning fields defined in anonymous class on toString call
                    System.out.println(test); //toString returns same
                    return data==test.getData() && text.equals(test.getText()); } return false;}
            public String toString(){return String.format("{data: %d; text: \"%s\"}", data, text);} };

        System.out.println(((Object)item).equals(item)); //returns false
    }
}
Comments