• Post Reply Bookmark Topic Watch Topic
  • New Topic

interface  RSS feed

weiliu lili
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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(){
} };
public static void main(String[] args){
Test t = new Test();
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?
Ajith Kallambella
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here 'a' is an instance of an an anonymous class that implements the interface 'A'.
When you create an anonymous class using the syntax
objRef = new SomeClassOrInterface(){}
it means one of the following -
  • if SomeClassOrInterface is a concrete class, the anonymous class implicitly extends the class SomeClassOrInterface.
  • if SomeClassOrInterface is an interface, then the anonymous class should and must implement the interface SomeClassOrInterface.

  • Lastly, since 'a' is defined as interface type 'A' and since the anonymous class correctly implements the interface A by providing non-abstract definition of method public void innerMeth(), the reference 'a' can be legally assigned to an instance of the anonymous class.
    In a nutshell, what you are creating here, is an object of type that implements the interface. You are not trying to instantiate the interface itself, which ofcourse, is not possible!.
    Hope that helps!
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!