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

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

  •  12-10-2019
  •  | 
  •  

Question

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

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

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

Was it helpful?

Solution

No. it is not compilable.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top