Java Modifying a Class Directly, null Reference?

I am new to using the new CLASS_NAME () {STUFF} Java function, but what I met 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 think the output of this program will be:

abc

abc

abc

Instead it is:

abc

null

abc

I am really confused why this is so. I taught myself this function myself, so I really know little about it. Any help is appreciated. Thanks!

+4
source share
1 answer

They are called anonymous classes.

Polymorphism does not apply to fields. When you do

System.out.println( e.a );

a / e, Test. , null.

a

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

hiding .

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

.

+7

All Articles