Override method, why can't I referenciate new own methods?

风格不统一 提交于 2019-12-24 12:43:31

问题


I don't understand this:

OnGlobalLayoutListener listener = new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
         System.out.println("I am override a method");
    }

    public void hello(){
         System.out.println("This is a new method");
    }
};

//listener.hello(); Why I cannot do it?

Without this I can do it:

new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
             System.out.println("I am override a method");
        }

        public void hello(){
             System.out.println("This is a new method");
        }
    }.hello();

Why in the first case cannot I invoke the method hello() and the second case I can do it?


回答1:


You're creating a new anonymous type, with a new method called hello.

You can call hello on the expression new OnGlobalLayoutListener() { } because the type of that expression is your new anonymous type.

You can't call hello on listener because the compile-time type of listener is OnGlobalLayoutListener, which doesn't have a hello method.

If you want to add extra methods, I would personally suggest you create a new nested class within your current class. You can declare a new named class right within a method, but I wouldn't advise it, just in terms of the clutter it creates.

Note that the overriding of onGlobalLayout is completely irrelevant to the question. You'd see the same thing if you tried writing:

new Object {
    public void hello() { ... }
}



回答2:


In both cases, you instantiate an object by creating an anonymous inner class, but the way you reference the hello()method differs:

In the first case, you assign the instantiated class to a reference of the OnGlobalLayoutListener interface. The problem is that the interface has not declared the hello() method, so it cannot be called. However, there is no problem if you try calling the onGlobalLayout().

In the second case, the hello() method is accessible, because you call it on reference of the class that was just instantiated. In contrast to the interface, the class has two methods, the overriden onGlobalLayout() and the requested hello() method.



来源:https://stackoverflow.com/questions/11914493/override-method-why-cant-i-referenciate-new-own-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!