Java 中的匿名对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24916639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:37:36  来源:igfitidea点击:

Anonymous Objects in Java

java

提问by pnkjshrm30

Java helps us creating anonymous object using

Java 帮助我们使用创建匿名对象

new class_name();

statement and calling the methods using association(.) operator like

语句并使用关联(。)运算符调用方法,如

new Emp().input();

How can I use it to invoke two methods simultaneously from an anonymous object like invoking both input()and show()together ?

我怎么能同时使用它来调用两种方法从诸如调用两个匿名对象input()show()在一起?

回答by Zach

How about making a method:

如何制作一个方法:

public void inputThenShow() {
    input();
    show();
}

Then call with

然后用

new Emp().inputThenShow();

回答by Sebas

or

或者

public Emp show() {
    // do the stuff
    return this;
}
public Emp input() {
    // do the stuff
    return this;
}

Then call with

然后用

new Emp().show().input();

回答by njzk2

What you can also do, without modifying the Empclass, is create an anonymous class that extends your class to allow it to call both methods.

您还可以在不修改Emp类的情况下创建一个匿名类来扩展您的类以允许它调用这两种方法。

new Emp() {
    public void doStuff() {
        input();
        show();
    }
}.doStuff();

Which as a bonus gives you an anonymous instance of an anonymous class.

作为奖励,您可以使用匿名类的匿名实例。