I have an example class defined like below:
public class FooBar {
void method1(Foo foo){ // Should be overwritten
...
}
}
Later, when I try this:
FooBar fooBar = new FooBar(){
public String name = null;
@Override
void method1(Foo foo){
...
}
};
fooBar.name = "Test";
I get an error saying that the name field does not exist. Why?
Because the type of the variable
"fooBar"isFooBar(the run-time type of the object in said variable is that of the anonymous class implementingFooBarwhich is also a subtype ofFooBar)……and the type
FooBardoes not have said member. Hence, a compile error. (Remember, the variable"fooBar"can contain any object conforming toFooBar, even those withoutname, and thus the compiler rejects the code which is not type-safe.)Edit: For one solution, see irreputable’s answer which uses a Local Class Declaration to create a new named type (to replace the anonymous type in the post).
Java does not support a way to do this (mainly: Java does not support useful type inference), although the following does work, even if not very useful:
Happy coding.
Both Scala and C# support the required type inference, and thus anonymous type specializations, of local variables. (Although C# does not support extending existing types anonymously). Java, however, does not.