+ 3
Can we declare a method inside another method..??means nested methods..
I saw 👀 Java version 7 and below were not allowed to do nested methods then how can we achieve this... class MyClass { public static void main(String[] args) { public static void display() { // something like this... } } IS IT CORRECT...🧐
7 Antworten
+ 15
♡Nani《 King Of Pain 》♡
Yes you can but not "directly"
https://www.xspdf.com/resolution/10302515.html
+ 1
Java does not support “directly” nested methods. Many functional programming languages support method within method. But you can achieve nested method functionality in Java 7 or older version by define local classes, class within method so this does compile. And in java 8 and newer version you achieve it by lambda expression.
+ 1
public class Test {
static void Foo()
{
// local class
class Local {
void print()
{
System.out.println("works!");
}
}
new Local().print();
}
public static void main(String[] args)
{
Foo();
}
}
https://code.sololearn.com/cebZYP3KZ1dw/?ref=app
This would be a possible way or in lambda
public class Test {
interface myInterface {
void run();
}
// run() using Lambda expression
static void Foo()
{
// Lambda expression
myInterface r = () ->
{
System.out.println("works");
};
r.run();
}
public static void main(String[] args)
{
Foo();
}
}
+ 1
Piyush Thank you 😊
0
Julian Bents thanks 🙏 for help
0
Runnable method = () -> System.out.println("method");
method.run();
0
Yes you can