javapolymorphismanonymous-class

Methods of anonymous classes in Java


Is there a way to capture the type of an anonymous class?

In the following example, how can i invoke the method g2 of the anonymous class? can't think of a specific case that it would be absolutely useful. and i'm aware that anonymous classes are for "on-the-fly" use. however, wondering.

If i can't invoke it, what's the use of being able to define it (if any-- other than being a helper to other methods of the anonymous class itself) in the anonymous class?

// http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

public class SomeClass {

    abstract class HelloWorld {  abstract public void greet();  }

    public void sayHello() {        
        class EnglishGreeting extends HelloWorld {  //  local class 
            String name = "world";
            public void greet() {  System.out.println("Heya " );    }
            public void gg() { System.out.println("do this as well.. ");}  }  
        HelloWorld englishGreeting = new EnglishGreeting();

        HelloWorld frenchGreeting = new HelloWorld() {  //  anonymous class 
            public void g2() { System.out.println("do this too.. ");}
            public void greet() {  System.out.println("Salute ");  }
        };  


        englishGreeting.greet();
        ((EnglishGreeting)englishGreeting).gg();
        frenchGreeting.greet();
//        ((frenchGreeting.getClass())frenchGreeting).g2();  // gives a checked error
    }  

    public static void main(String... args) {
        SomeClass myApp = new SomeClass();
        myApp.sayHello(); 
}            
}

Note: saw Can't call anonymous class method & Anonymous Inner Classes Inside Methods along with some other relevant discussions.

TIA.

//==============================================

EDIT:

the below worked-- one step closer to it for whatever its worth. not looking up its reference type when the method is invoked right on the new object.

        HelloWorld frenchGreeting = new HelloWorld() {
            public HelloWorld g2() { System.out.println("do this too.. ");  return this; }
            public void greet() {  System.out.println("Salute ");  }
        }.g2();  

Solution

  • You can only call it directly, e.g.

    new HelloWorld() {
        // ...
    }.g2();
    

    However, notice that you can't assign the variable and call it directly, and you can't call it elsewhere in the method. Still, this is the closest thing I could think of to answering your question.