Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Modifying a Class Directly, null Reference?

I am new to using Java's new CLASS_NAME() { STUFF } feature, but what I have come across seems strange. Consider the following code:

class Test
{
    public String a;
    public static void main( String[] args ) throws java.lang.Exception
    {
        String j = "abc";
        //Emulating passing an argument as I did in my code.//
        final String s = j;
        Test v = new Test();
        v.a = s;
        Test e = new Test() {
            public String a = s;
        };
        Test g = new Test();
        g.a = s;
        System.out.println( v.a );
        System.out.println( e.a );
        System.out.println( g.a );
    }
}

I would think the output of this program would be:

abc

abc

abc

Instead it is:

abc

null

abc

I am really confused as to why this is. I self taught myself this feature, so I really don't know much about it. Any help is appreciated. Thanks!

like image 386
The Floating Brain Avatar asked Mar 22 '23 03:03

The Floating Brain


1 Answers

These are called anonymous classes.

Polymorphism doesn't apply to fields. When you do

System.out.println( e.a );

the field a is being resolved on the declared/static type of e which is Test. And since you haven't explicitly initialized it, it defaults to null.

Your declaration a field called a in the anonymous class

Test e = new Test() {
     public String a = s;
};

is hiding the field of the same name in its parent class.

You could instead use an initialization block

Test e = new Test() {
    {
        a = s;
    }
};

since the field is accessible to the sub-classes.

like image 109
Sotirios Delimanolis Avatar answered Mar 31 '23 22:03

Sotirios Delimanolis