I have an example class defined like below:
public class FooBar {
void method1(Foo foo){ // Should be overwritten
...
}
}
Later,
fooBar
is a reference to an object of type foobar
, and such objects do not have a field name
. Simple as that. And since it’s an anonymous type, the only way to reference that field is through its this
reference.
As everyone said, this is due to static typing and FooBar
class does not contain name
. So it won't work.
I wanted to point out the suggested usage of Anonymous class.
Anonymous class (or close to Closures, maybe lambdas. Similar but not same) come from functional programming paradigm, where the states should be immutable.
That being said, why should you user such classes? When you need a quick and short thing to be done which should not necessarily go in a complete class. Example:
MyTask() //This is a method
{
new Thread(new Runnable() { //Anonymous class
public void run()
{}
}).start();
}
The understanding of enclosing your implementation only to a function/class is important.
The scope of the variables defined in the Anonymous class (or closed-over function) should only be used inside the Anonymous class
, it cannot be accessed from other program code.
Therefore, you should not (and anyway cannot) set fooBar.name = "Test";