2011-01-19 152 views
2

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

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

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

+2

你觉得没错。 – 2011-01-19 13:46:36

+0

甚至没有构造函数内的构造函数? – 2011-01-19 13:49:38

+1

会有什么意义?构造函数创建类的实例,而不是其他构造函数的实例:) – 2011-01-19 13:55:16

回答

5

。它不是可编译的。

2

不,Java只允许在类中定义一个方法,而不是在另一个方法中定义。

3

不是直接的,但你可以在一个类的方法中的方法:

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

这是不可能在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); 
    } 
} 
相关问题