Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 648
Scorpion Avatar asked Feb 14 '23 15:02

Scorpion


2 Answers

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
like image 56
Mik378 Avatar answered Feb 16 '23 05:02

Mik378


new MyObject(){
    public MyObject open(){ 
        // do some stuff
        return this;
    }
     public MyObject dis(){ 
        // do some stuff 
        return this;
    }
}.open().dis();
like image 21
JamesB Avatar answered Feb 16 '23 05:02

JamesB