Why can't I create a new method in an anonymous inner class?

后端 未结 3 990
余生分开走
余生分开走 2021-01-28 10:25

If I have the following class:

public class TestObject {
  public String Hooray() {
    return \"Hooray!\";
  }
}

I can obviously instantiate t

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-28 10:46

    You can create the method, there's nothing wrong with your Boo method (apart from the fact that it has a capital letter at the front). The problem is that outside of the anonymous class, the Boo method is not available (it is not exposed as part of the API of the class).

    This is the same with any class that implements an interface... if the class has methods (even public methods) that are not part of the interface then you need to cast the instance to the specific class in order to access these methods.

    Unfortunately, because this is an anonymous class, you can't cast it (you don't know what to cast it to).

    These internal methods can still be useful, but you have to call them from inside the anonymous class, not from outside.

提交回复
热议问题