What will happen if you try to compile and run this ?
interface A{
public void innerMeth();
}
public class
Test {
A a;
int memVar = 1;
void aMethod(){
a = new A(){
public void innerMeth(){
System.out.println(memVar);
} };
}
public static void main(
String[] args){
Test t = new Test();
t.a.innerMeth();
}
}
1. Compiler error.
2. NoSuchMethodException at runtime.
3. Compiles and runs printing 1
4. Throws a NullPointerException at runtime.
correct answer/s :4
You will get a NullPointerException because the
inner class object gets assigned to the reference a
only after the aMethod() runs. You can prevent
the exception by calling t.aMethod() before the
inner anonymous class method is called.
My problem: a=new A(){} in which A is an interface which can not be used as instantiation of an object. but why I m wrong?