1

why is it necessary to save the name of java program with the main class name when that class is public, if the class is not public then we can save the program with any name and then can compile it. why in case of public main class we can not do that.?

madth3
  • 7,275
  • 12
  • 50
  • 74
Ankit Saxena
  • 19
  • 1
  • 2
  • 3
    I'm afraid your question is fairly unclear. Perhaps some code examples of what you think you can and can't do would help. (Also: "Save" *where*?) – T.J. Crowder Mar 19 '13 at 18:05
  • 1
    @LoganDam While your edit might be correct I think the OP is maybe confused about some things and could benefit from some clarifications. Those clarification would not happen with the way you rewrote the question. – madth3 Mar 19 '13 at 18:23
  • @madth3: Indeed, it wasn't at all clear to me that the edit didn't change things. – T.J. Crowder Mar 19 '13 at 18:28

2 Answers2

0

I think the question means, why does a public class name needs to match the name of the file it's been declared in.

I think this answer by Bill K would answer your question:

https://stackoverflow.com/a/2134888/1401409

Community
  • 1
  • 1
scharette
  • 605
  • 1
  • 9
  • 25
0

No it is not necessary . You can save the file containing class say MainClass containing main method with any other name say NonMainClass.java (given that the file doesn't contain any other public class). You can compile the same using javac NonMainClass.java . But when executing it you need to execute it using java MainClass.

For Example. Consider the code given below:

class MainsClass 
{
    public static void main(String[] args) 
    {
        System.out.println("Hello World!");
    }
}

This file is saved as NoMainClass.java. And it is compiled as javac NoMainClass.java. It generates the MainClass.class in working directory. And to execute the program you need to run following command java MainClass .

Vishal K
  • 12,976
  • 2
  • 27
  • 38