在Java中,方法/构造函数声明可以在另一个方法/构造函数声明中出现吗?
-
12-10-2019 - |
题
在Java中,方法/构造函数声明可以在另一个方法/构造函数声明中出现吗?例子:
void A() {
int B() { }
}
我认为不是,但我很想放心。
解决方案
不. 。它是不可编译的。
其他提示
不是直接的,但是你 能够 在类中有一种方法:
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仅允许在类中定义一种方法,而不是在其他方法中。
不隶属于 StackOverflow