I receive a compiler error whenever I attempt to invoke a method belonging to an anonymous class from the outer class. Example:
public class Test {
public static void main(String[] args) {
Test testObj = new Test(){
public void doStuff(){
System.out.println("Test");
}
};
testObj.doStuff();
}
}
The error the compiler provides is simply "Cannot find symbol - doStuff()". I must be overlooking something...any ideas?
Thanks in advance.
You can only call existing method from the Reference of Test class. So if you have declared
doStuff()
method then only you can call it withTest testObj
reference.See this SO question Is it possible to call subclasses' methods on a superclass object?
But you can surely call new method inside other method declaration of anonymous class. See below example.
Example:
Output: