• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

interface

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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(){
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?
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
     
    reply
      Bookmark Topic Watch Topic
    • New Topic