简体   繁体   中英

Interface as a method's parameter

I have a problem with naming following situation

{...}

X.a;
a.addListener( new ListenerForX(){
// some interface methods
});

{...}

It is the same as:

{...} 
X.a;
a.addListener( new XListener());
{...} 
private class XListener implements ListenerForX{
//some methods
}

How is it called?

The first code example is called anonymous inner class .

Both examples are valid in Java. The method is just interested in ListenerForX and doesn't care about the implementation thereof.

The first one is an anonymous inner class.

Say you have an interface Walkable with doWalk () ,

For a method that takes in a Walkable instance you could write something like .

takeForaWalk(new Walkable() {
 void doWalk() {
 //Impl
}}
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM