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.
SwingU
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
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.
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.
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