Nested functions in Java

后端 未结 6 1376
礼貌的吻别
礼貌的吻别 2020-11-27 15:53

Are there any extensions for the Java programming language that make it possible to create nested functions?

There are many situations where I need to create methods

6条回答
  •  再見小時候
    2020-11-27 16:23

    I think that the closest you can get to having nested functions in Java 7 is not by using an anonymous inner class (Jon Skeet's answer), but by using the otherwise very rarely used local classes. This way, not even the interface of the nested class is visible outside its intended scope and it's a little less wordy too.

    Jon Skeet's example implemented with a local class would look as follows:

    public class Test {
        public static void main(String[] args) {
            // Hack to give us a mutable variable we can
            // change from the closure.
            final int[] mutableWrapper = { 0 };
    
            class Foo {
                public void bar(int num) {
                    mutableWrapper[0] *= num;
                    System.out.println(mutableWrapper[0]);
                }
            };
    
            Foo times = new Foo();
    
            for (int i = 1; i < 100; i++) {
                mutableWrapper[0] = i;
                times.bar(2);
                i = mutableWrapper[0];
    
                times.bar(i);
                i = mutableWrapper[0];
            }
        }
    }
    

    Output:

    2
    4
    10
    100
    

提交回复
热议问题