Create an anonymous inner class and call its methods

I was looking for this, but unfortunately I could not find any matches, I have this local anonymous inner classinside a method like this: -

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

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

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

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

+4
source share
3 answers

You can 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, an interface is only needed if a link is assigned. In fact, the following solution is true (called by @JamesB):

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

but this did 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
+6
new MyObject(){
    public MyObject open(){ 
        // do some stuff
        return this;
    }
     public MyObject dis(){ 
        // do some stuff 
        return this;
    }
}.open().dis();
+1

If you want to call methods from an anonymous class, this means that it extends the superclass or implements the interface. Thus, you can simply store this instance in the parent link and call it all contract 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();
+1
source

Source: https://habr.com/ru/post/1530116/


All Articles