views:

99

answers:

2

Netbeans is creating a class Main automatically when I create a new project.

so its in the constructor here i write the code and use all other classes?

What happens when I rename the Main class to something else. Will it still work?

+2  A: 

It won't work, only because the name of the topmost class in a Java file must be named the same as the file itself. IE the Main class needs to be in the file Main.java. If you rename both the class and the file it will work.

so its in the constructor here i write the code and use all other classes?

It's generally bad practice to put all of your code inside the constructor. The constructor is generally used for setup, like initializing the fields of the class. You should separate your logic out into methods of the class, which can include calling methods on instances of other classes.

And if you want to make your Main class an executable, you would write that code in a function with signature public static void main(String[] args), and then execute your (compiled) class like java Main in the directory where Main.class resides, though NetBeans likely provides you with a way to execute through the IDE as well.

danben
Oh sorry somehow I understood your answer wrong. Of course what you say is true. I just wanted to point out that the class can be named to anything. The class name and file name does not play any role as entry point for the application. And assume that the OP sees a relation between the class `Main` and the method `main`. Sorry for the misunderstanding.
Felix Kling
(danben, to give your voters a chance to change their votes, please edit your answer - otherwise they can't change it)
Andreas_D
And yes it is correct that the class can be renamed to any valid Java class name, but then it is important to note that the name of the file must change also (which was what I had written in the first place).
danben
@Andreas_D: I know, and I did, but thanks.
danben
As I said I read your answer to quickly and still had the `main` method in my mind. Sorry.
Felix Kling
No problem, it happens.
danben
A: 

You can rename class Main, important is function main ( public static ). In project configuration you can choose which class contains main function ( method ). But when you rename class then you have to rename file as well as class.

The constructor of this class is not important because main method is static so there is no instance of this class. You can create if manually if you want.

Gaim