+ 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...🧐

28th Dec 2020, 11:46 AM
❤☆Nani☆❤
❤☆Nani☆❤ - avatar
7 ответов
28th Dec 2020, 12:06 PM
Piyush
Piyush - avatar
+ 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.
28th Dec 2020, 11:58 AM
Julian Bents
Julian Bents - avatar
+ 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();     } }
28th Dec 2020, 12:00 PM
Julian Bents
Julian Bents - avatar
+ 1
Piyush Thank you 😊
28th Dec 2020, 12:12 PM
❤☆Nani☆❤
❤☆Nani☆❤ - avatar
0
Julian Bents thanks 🙏 for help
28th Dec 2020, 12:18 PM
❤☆Nani☆❤
❤☆Nani☆❤ - avatar
0
Runnable method = () -> System.out.println("method"); method.run();
28th Dec 2020, 9:34 PM
zemiak
0
Yes you can
29th Dec 2020, 5:30 PM
Yash Chaudhari
Yash Chaudhari - avatar