Java – inline class definition

I've seen several similar examples in Java, and I hope someone can explain what happened It seems strange to me that a new class can be defined inline Expect the first printout line because it's just toString But the second one seems to override the function internally Is there a technical term? Or any more in-depth documents? thank you!

If I have the following code:

public class Apple {
    public String toString() {
        return "original apple";
    }
}

public class Driver {
    public static void main(String[] args) {
        System.out.println("first: " + new Apple());
        System.out.println("second: " + 
            new Apple() {
                public String toString() {
                    return "modified apple";
                }
            }
        );
    }
}

Code output:

first: original apple
second: modified apple

Solution

This is an anonymous inner class You can find more information about inner classes in the Java documentation link Editor: I added a better link to describe anonymous inner classes, because the Java document left something needed/ edit

Most people will use anonymous inner classes to define listeners Consider this:

I have a button. When I click it, I want it to show something to the console But I don't want to create a new class in a different file. I don't want to define an internal class in this file later. I want to use logic here immediately

class Example {
    Button button = new SomeButton();

    public void example() {
        button.setOnClickListener(new OnClickListener() {
            public void onClick(SomeClickEvent clickEvent) {
                System.out.println("A click happened at " + clickEvent.getClickTime());
            }
        });
    }

    interface OnClickListener {
        void onClick(SomeClickEvent clickEvent);
    }

    interface Button {
        void setOnClickListener(OnClickListener ocl);
    }
}

This example is weird and obviously incomplete, but I think it's an idea

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>