aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "interface " Watch "interface " New topic
Author

interface

weiliu lili
Ranch Hand

Joined: Apr 11, 2002
Posts: 46
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?
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
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!


    Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: interface