+ 2

Can you have methods inside the main method?

As mentioned in the title, can you create methods inside the main method as shown below, because when compiled in an IDE, it shows an error. public static void main(String[ ] args) { Machine m = new Machine() { @Override public void start() { System.out.println("Wooooo"); } };

15th Jan 2017, 2:48 PM
Yohan Punchihewa
Yohan Punchihewa - avatar
3 Answers
+ 2
You can, but you may be missing some key details about anonymous classes in Java. Check out https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#declaring-anonymous-classes . Note that when using anonymous classes, you use an interface. Without seeing the error or declaration of Machine, I can't tell you exactly what the issue is.
15th Jan 2017, 2:54 PM
Lauren
0
great job
23rd Feb 2017, 5:33 PM
Md. Milon Hossain
Md. Milon Hossain - avatar
- 1
if you are using anonymous class then you must create it's object at the time of class creation itself
15th Jan 2017, 3:11 PM
Vishnu Sivan
Vishnu Sivan - avatar