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!
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.
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