简体   繁体   中英

How can we call methods overridden in a java anonymous class?

Consider the code below :

abstract class AbstractClass {
  abstract m1();
}

public class Test {
  public static void main(String [] args) {
    AbstractClass obj = new AbstractClass() {
      @Override void m1() { 
        System.out.print("Instance of abstract class !");
      }
    };
    obj.m1();
  }
}

Now here is what I did not understand about this code.
I read that anonymous class creates the class with unknown name which extends the class whose reference is provided (here it is abstract AbstractClass).

Also I remember that we cannot implement the method of child class if the the object is having reference of parent class.

see block of code below

Parent obj = new Child();
obj.methodOfParent();
obj.methodOfChild();  //this gives error

Now here is my point if Anonymous Class extends its Parent Class whose reference is provided, then how can we call overriden methods of Parent Class from Anonymous Class?

There is a difference between calling an overridden method of parent and calling a method of child. If a method is declared in class T , you can call it on a variable statically typed as T , regardless of where the method is actually implemented.

In your example, if obj.methodOfParent() happens to be a method override from Child , the method in Child will run, even though obj 's static type is Parent .

Same mechanism is in play with anonymous classes: the reason that you are allowed to call obj.m1() is that m1() has been declared in the parent class.

I guess you just miss one point. Let me show you example:

class Parent {
  public void methodOfParent() {}
  public void methodOfParentToBeOverriden() {}
}
class Child extends Parent {
  @Override public void methodOfParentToBeOverriden() {}
  public void methodOfChild() {}
}

Parent obj = new Child();
obj.methodOfParent(); //this is OK
obj.methodOfParentToBeOverriden(); // this is OK too
obj.methodOfChild();  //this gives error  
((Child)obj).methodOfChild();  //this is OK too here.

Please note that when you call obj.methodOfParentToBeOverriden() it will be called implementation from Child class. Independence did you cast this object to Parent type or not.

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