简体   繁体   English

覆盖方法,为什么我不能引用新的自己的方法?

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

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? 为什么在第一种情况下我不能调用方法hello()和第二种情况我能做到吗?

You're creating a new anonymous type, with a new method called hello . 您正在使用名为hello的新方法创建一个新的匿名类型。

You can call hello on the expression new OnGlobalLayoutListener() { } because the type of that expression is your new anonymous type. 您可以在表达式new OnGlobalLayoutListener() { }上调用hello ,因为该表达式的类型您的新匿名类型。

You can't call hello on listener because the compile-time type of listener is OnGlobalLayoutListener , which doesn't have a hello method. 可以不hellolistener因为编译时类型listenerOnGlobalLayoutListener ,其中没有一个hello方法。

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. 请注意, onGlobalLayout的覆盖与问题完全无关。 You'd see the same thing if you tried writing: 如果你尝试写作,你会看到同样的事情:

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

In both cases, you instantiate an object by creating an anonymous inner class , but the way you reference the hello() method differs: 在这两种情况下,您都可以通过创建匿名内部类来实例化对象,但引用hello()方法的方式有所不同:

In the first case, you assign the instantiated class to a reference of the OnGlobalLayoutListener interface . 在第一种情况下,将实例化的类分配给OnGlobalLayoutListener 接口的引用。 The problem is that the interface has not declared the hello() method, so it cannot be called. 问题是接口没有声明hello()方法,因此无法调用它。 However, there is no problem if you try calling the onGlobalLayout() . 但是,如果您尝试调用onGlobalLayout() ,则没有问题。

In the second case, the hello() method is accessible, because you call it on reference of the class that was just instantiated. 在第二种情况下,可以访问hello()方法,因为您在刚刚实例化的类的引用上调用它。 In contrast to the interface, the class has two methods, the overriden onGlobalLayout() and the requested hello() method. 与接口相比,该类有两个方法,覆盖onGlobalLayout()和请求的hello()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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