gordon sung
gordon sung

Reputation: 605

Invoking a method in anonymous (inner) classes

 interface Example{
   void methodExample();
 }
 class Y{
  void do(Example x) { }
}

class X{
   void methodX() {
     Y y = new Y();
     y.do(new Example() {
       public void methodExample() {
         System.out.println("methodExample");
       } 
     });
   } 
 } 

I want to create a main class and call methodExample. How would I do that?

Upvotes: 2

Views: 352

Answers (2)

Darshan Mehta
Darshan Mehta

Reputation: 30809

If you don't have access to class Y then, the only way to do is to override doIt() itself first, using anonymous inner class and then, call the overridden method, e.g.:

class X {
    void methodX() {
        Y y = new Y() {
            @Override
            void doIt(Example x) {
                x.methodExample();
            }
        };
        y.doIt(new Example() {
            public void methodExample() {
                System.out.println("methodExample");
            }
        });
    }
}

To call this, you can simply do:

public static void main(String[] args) throws Exception {
    X x = new X();
    x.methodX();
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Since your class implements Example interface, and because void methodExample() is present on that interface, all you need to do is to reference the object by its interface, and call its method:

class Y{
    public void doIt(Example x) {
        x.methodExample();
    }
}

The above works, because objects of all classes implementing Example, including all anonymous implementations, are known at compile time to implement methodExample().

Upvotes: 3

Related Questions