简体   繁体   中英

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?

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() { ... }
}

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.

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