在Java中,方法/构造函数声明可以在另一个方法/构造函数声明中出现吗?

StackOverflow https://stackoverflow.com/questions/4735922

  •  12-10-2019
  •  | 
  •  

在Java中,方法/构造函数声明可以在另一个方法/构造函数声明中出现吗?例子:

void A() { 
    int B() { }
}

我认为不是,但我很想放心。

有帮助吗?

解决方案

. 。它是不可编译的。

其他提示

不,这是不可能的。以供参考: http://download.oracle.com/javase/tutorial/java/javaoo/methods.html

不是直接的,但是你 能够 在类中有一种方法:

class A {
    void b() {
        class C {
            void d() {
            }
        }
    }
}

这在Java中是不可能的。但是,尽管代码变得复杂,但这可以通过接口实现。

interface Block<T> {
  void invoke(T arg);
}
class Utils {
  public static <T> void forEach(Iterable<T> seq, Block<T> fct) {
    for (T elm : seq)
      fct.invoke(elm);
  }
}
public class MyExample {
  public static void main(String[] args) {
    List<Integer> nums = Arrays.asList(1,2,3);   
    Block<Integer> print = new Block<Integer>() {
      private String foo() {    // foo is declared inside main method and within the block
        return "foo";
      }
      public void invoke(Integer arg) {  
        print(foo() + "-" + arg);
      }
    };
    Utils.forEach(nums,print);
  }
}

不,Java仅允许在类中定义一种方法,而不是在其他方法中。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top