2

Is it possible to access the getVal() function inside displayMsg () function? I tried to create an annonymous inner-class with function getVal() and I want to call the getVal() function inside the displayMsg() function of the AnonymousClass.

import java.io.*;
class AnonymousClass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        displayMsg(new AnonymouseEx(10){
            public int getVal(){
                return getValue();
            }
        });

    }
    static void displayMsg(AnonymouseEx obj)
    {

    }
}
class AnonymouseEx{
    private int i=0;
    AnonymouseEx(int val)
    {
        i = val;
    }
    int getValue()
    {
        return i;
    }
}
Aravind Pilla
  • 416
  • 4
  • 14

1 Answers1

0

No this is not possible.

displayMsg expects a class of type AnonymouseEx which does not have a method called getVal. Because you only added this function to your anonymous subclass, other subclasses might not have this function, so displayMsg can not use it.

If you want to give a custom implementation used in an anonymous class, you have override a function in AnonymouseEx or give it an abstract method that subclasses must implement. Using the abstract method (or an interface) is most common, for instance in the Listener interfaces that Java uses.

Thirler
  • 20,239
  • 14
  • 63
  • 92