开发者

In Java, can a method/constructor declaration appear inside another method/constructor declaration?

开发者 https://www.devze.com 2023-02-05 06:28 出处:网络
In Java, can a method/constructor declaration appear inside another method/constructor declaration? Example:

In Java, can a method/constructor declaration appear inside another method/constructor declaration? Example:

void A() { 
开发者_StackOverflow社区    int B() { }
}

I think not, but I'd love to be reassured.


No. it is not compilable.


No this is not possible. For reference: http://download.oracle.com/javase/tutorial/java/javaOO/methods.html


Not directly, but you can have a method in a class in a method:

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


This is not possible in java. However this can achieved by interface though the code becomes complex.

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);
  }
}


No, Java only allows a method to be defined within a class, not within another method.

0

精彩评论

暂无评论...
验证码 换一张
取 消