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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With