This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why can't a method be inside the main public static main method?  RSS feed

 
Doyle Davis
Greenhorn
Posts: 4
Java Mac OS X Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do methods have to be outside the public static main method? In the code below, I kept getting the following error
illegal start of expression
void talk(){

when I compiled the program. I had to comment out the code and place a copy of the method
outside the public static void main method as shown below. Then it ran ok.


class Speak{

public static void main(String[] args){
Speak one = new Speak();
one.talk();

//void talk(){
//System.out.println("hello");
//}


} // end of main method


void talk(){
System.out.println("hello");
}


} // end of Speak class
 
Ralph Cook
Ranch Hand
Posts: 479
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short answer is that it is illegal because it does not have a defined meaning.

Methods cannot be defined within other methods because there is no language rubric for them to be put within another method. There is no "scope" for a method definition that makes sense within another method; you cannot "dereference" a method to invoke a method defined within it (main().talk() means something else).

The question is really more why you think this construction is legal, or just what you think it means. You can't put a method definition there because the compiler doesn't know what you mean by that, and neither do the rest of us.

rc
 
fred rosenberger
lowercase baba
Bartender
Posts: 12541
48
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
languages have EXTREMELY specific definitions of what is allowed and what is not. The Java Language Specification are those rules for this language, and are available for anyone to read. You can even write your own compiler, if you like.

Those rules simply do not allow for you to have a method defined inside another method. The creators felt there was no reason to do so, an attempting it would cause more problems (for the compiler writers) than it was worth.

What do you feel you could gain by doing it that you can't get by not nesting methods?
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!