En Java, puede una declaración de método / constructor aparecer dentro de otra declaración de método / constructor?
-
12-10-2019 - |
Pregunta
En Java, puede una declaración de método / constructor aparecer dentro de otra declaración de método / constructor? Ejemplo:
void A() {
int B() { }
}
Creo que no, pero me encantaría estar tranquilos.
Solución
No. it is not compilable.
Otros consejos
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.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow