简体   繁体   中英

Anonymous class method access

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.

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();

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.

The method can be called from within your anonymous class. And the more typical use of this construct is cases where you are implementing an interface (for a GUI listener for example), so the method will be known since it's an implementation of the interface the caller is expecting.

The reason why the compiler does not restrict the visibility of anonySubClassMethod to private is that this method can be accessed by means of reflection: obj.getClass().getMethod("anonySubClassMethod").invoke(obj)

If you don't want to use reflection, there's no way to invoke this method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM