2011-01-19 146 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); 
    } 
} 
相關問題