I am testing the snippet below, I need to know how can I access t.x or t.hello? What is its scope? Do developers define variables in this way?
public class Test{
As written, neither x nor hello can be accessed outside the object referenced by t. The problem is that they are only declared in t's anonymous class. They are not defined in Test, and it is not possible to cast the t reference to the type in which they are declared, because it is anonymous.
I have modified Test to make it abstract and add an abstract declaration of hello, allowing it to be called from outside the object referenced by t. I have also modified hello to add a use of x. Those changes illustrate the two ways of accessing anonymous class features - though the base class or internally.
public abstract class Test {
abstract void hello();
public Test() {
System.out.print("constructor\n");
}
public static void main(String[] args) {
Test t = new Test() {
int x = 0;
// System.out.print("" + x);
void hello() {
System.out.print("inside hello\n");
System.out.print("My value of x is "+x);
}
};
t.hello();
}
}