Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous class method access

Tags:

java

Is it any possible way to access the anonySubClassMethod method? If no why Java compiler allowing to create this method?

abstract interface AnonyIfc {
   public abstract void methodIfc ();
}

public class AnonyImplementation {
   public static void main (String... a) {
      AnonyIfc obj = new AnonyIfc(){
         public void methodIfc() {
            System.out.println("methodIfc");
         }
         public void anonySubClassMethod() {
            System.out.println("anonySubClassMethod");
         }
      };
      //obj.anonySubClassMethod()  won't be visible since refering sub class
      //                           method with super class reference
   }
 }

Update
From Francis Upton I understood that anonySubClassMethod can be used within the anonymous class. So can i expect the java compiler to restrict the access specifier to private for anonySubClassMethod? Hope there will be a reason for this public specifier also. just curious.

like image 734
Kanagavelu Sugumar Avatar asked Dec 03 '22 00:12

Kanagavelu Sugumar


2 Answers

As others have noted, the method might be called from within the class. The only way to call it from outside the class (besides using reflection) would be like the following:

new Object() {
    void doSomething() {
        //code
    }
}.doSomething();
like image 98
Paul Bellora Avatar answered Dec 07 '22 22:12

Paul Bellora


You could use reflection to access it, but otherwise there's no way to get to it from any code outside the anonymous class. But that doesn't mean you couldn't access it from within the class. methodIfc() could call it, and so that's why the compiler can't easily declare it to be dead code.

like image 25
Ernest Friedman-Hill Avatar answered Dec 07 '22 23:12

Ernest Friedman-Hill