pnkjshrm30
pnkjshrm30

Reputation: 81

Anonymous Objects in Java

Java helps us creating anonymous object using

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 ?

Upvotes: 7

Views: 13720

Answers (3)

Sebas
Sebas

Reputation: 21542

or

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

Then call with

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

Upvotes: 13

njzk2
njzk2

Reputation: 39405

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

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

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

Upvotes: 1

Zach
Zach

Reputation: 4792

How about making a method:

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

Then call with

new Emp().inputThenShow();

Upvotes: 4

Related Questions