Scorpion
Scorpion

Reputation: 587

Build an anonymous inner class and call its methods

I searched for this but unfortunately failed to find matches, I have this local anonymous inner class inside a method like this:-

new Object(){
    public void open(){
        // do some stuff
    }
    public void dis(){
        // do some stuff
    }
};

with 2 methods inside it (open,dis) and I know that if I want to use anyone of them just do

new Object(){
    public void open(){
        // do some stuff
    }
    public void dis(){
        // do some stuff
    }
}.open()

Now my question is What if I want to call the two methods at the same time How can I do this ?

Upvotes: 4

Views: 204

Answers (3)

robermann
robermann

Reputation: 1722

If you want to call methods from an anonymous class, that means it extends a superclass or implements an interface. So you can simply store in a parent's reference that instance and call on it all the contract's methods:

interface MyAnonymous {
   void open();
   void dis();
}

MyAnonymous anon = new MyAnonymous () {
    public void open(){
        // do some stuff
    }
    public void dis(){
        // do some stuff
    }
};

anon.open();
anon.dis();

Upvotes: 1

Mik378
Mik378

Reputation: 22171

You may create an interface like this:

interface MyAnonymous {
   MyAnonymous open();
   MyAnonymous dis();  //or even void here
}

new MyAnonymous(){
    public MyAnonymous open(){
        // do some stuff
        return this;
    }
    public MyAnonymous dis(){
        // do some stuff
        return this;
    }
}.open().dis();

EDIT ----

As @Jeff points out, the interface is needed only if the reference is assigned. Indeed, the following solution (evoked by @JamesB) is totally valid:

new MyObject(){
        public MyObject open(){
            // do some stuff
            return this;
        }
        public MyObject dis(){
            // do some stuff
            return this;
        }
    }.open().dis();

but this would not compile:

MyObject myObject = new MyObject(){
            public MyObject open(){
                // do some stuff
                return this;
            }
            public MyObject dis(){
                // do some stuff
                return this;
            }
        };
myObject.open().dis();  //not compiling since anonymous class creates a subclass of the class

Upvotes: 6

JamesB
JamesB

Reputation: 7894

new MyObject(){
    public MyObject open(){ 
        // do some stuff
        return this;
    }
     public MyObject dis(){ 
        // do some stuff 
        return this;
    }
}.open().dis();

Upvotes: 1

Related Questions