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 ?
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
new MyObject(){
public MyObject open(){
// do some stuff
return this;
}
public MyObject dis(){
// do some stuff
return this;
}
}.open().dis();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With