Passing code as function arguments

后端 未结 6 1530
星月不相逢
星月不相逢 2021-01-23 22:56

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         


        
相关标签:
6条回答
  • 2021-01-23 23:04

    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

    0 讨论(0)
  • 2021-01-23 23:08

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

    0 讨论(0)
  • 2021-01-23 23:10

    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.

    0 讨论(0)
  • 2021-01-23 23:14

    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.

    0 讨论(0)
  • 2021-01-23 23:16

    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.

    0 讨论(0)
  • 2021-01-23 23:20

    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

    0 讨论(0)
提交回复
热议问题