简体   繁体   中英

Passing code as function arguments

I was reading a textbook and I was wondering how come the argument we pass to the function is neither a primitive or an user-defined instance of a class.

SwingUtilities.invokeLater(new Runnable() 
{
    public void run() {
        new ButtonDemo();
    }
});

I have learned that it was either one of those two. But it seems here that it passes an user-defined constructor method, eg Runnable(). It seems they want to run the thread at a later time, but when? And is this even legal, I assume it is, but I never heard of such a thing in my Java class.

This is actually passing an instance of an anonymous inner class implementing the Runnable interface. Read about them in the Java tutorial .

I was wondering how come the argument we pass to the function is neither a primitive or an user-defined instance of a class.

It is an instance of a user-defined class. The only difference is that this class does not have a name * .

It is a real instance of a class, though - it can do most of the things a named class can do. Among other things, it can provide implementations of methods of its base class or an interface, which is what is used to pass "a piece of executable code" to a method.

* At least, not a user-visible one: Java compiler does assign each anonymous class an internal name, which usually contains a dollar sign.

The code inside SwingUtilities is something like this

private Runnable runnable;

private void invoke(){//called at some point from inside the runnable
     runable.run();
}
public void invokeLater(Runnable runnable){
     this.runnable=runnable;
}

These are called callbacks.

This called anonymous class, where you define a class for a single use and do not provide it a name.

To understand them better, refer to this tutorial: http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

Read about Anonymous Classes . This are treated as separate classes. If you compile your code and say the file name is Test.java . By compiling there will two class file Test.class and Test$1.class and if you have more inner classes you will have Test$2.class , Test$3.class and so on.

Passing code as function arguments

Java will have lambda expressions in release 8. It will worth checking out this as well: http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

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