简体   繁体   中英

Why can't we define main function in static inner classes?

I have the following simple code

public class Tester {
    static class TesterChild {
        public static void main(String args[]) {
            System.out.println("Test");
        }
    }
}

It compiles fine. But when I run it I get the following Error

[aniket@localhost src]$ java Tester
Error: Could not find or load main class Tester

Question is why can't we define our main method in static inner class?

Update1 :

As specified in the answers/comments I have change the code to following

public class Tester {
    public static class TesterChild {
        public static void main(String args[]) {
            System.out.println("Test");
        }
    }
}

I compiled it and it made two class files Tester.class and Tester$TesterChild.class . But still i am getting error

[aniket@localhost Desktop]$ java Tester$TesterChild
Error: Could not find or load main class Test

Update 2:

Ok now I included current directory in the classpath and executed still getting error

[aniket@localhost Desktop]$ java -cp . Tester$TesterChild
Error: Main method not found in class Tester, please define the main method as:
   public static void main(String[] args

It can be run as main but you are not using the right class. Your main class is not Tester but Tester.TesterChild .

In Eclipse it will run without any setup but from the command line you have to use the java 'yourpackage.Tester$TesterChild' syntax as others mentioned above.

You need to wrap the name of your class in '' s because on linux/unix the shell might think that $TesterChild is a variable. If you try it out in the prompt you will get something like this if you omit the '' s:

Error: Could not find or load main class Tester

If you need to explicitly set the classpath you can use the -cp or the -classpath option or you can set it from the commandline: set CLASSPATH=/somedir

Since you have defined main() method in inner class.
Run the inner class to get main() to be executed.

use command line java Tester$TesterChild .

I think you are placing java file in some package.If then use this command line.

java -cp . yourPackageName.Tester$TesterChild
For example I have placed file in a package named test .Then my command is like this

java -cp . test.Tester$TesterChild

Beware that the dollar sign has special meaning to most shells. Ie if you write java -cp . Tester$TesterChild java -cp . Tester$TesterChild your shell might replace $TesterChild with the contents of an environment variable with that name or silently replace it with nothing if it doesn't exist. Try java -cp . 'Tester$TesterChild' java -cp . 'Tester$TesterChild' or java -cp . Tester\\$TesterChild java -cp . Tester\\$TesterChild

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM