views:

100

answers:

4

I'm having problems when trying to compile the following code:

alt text

I first tried compiling with this code:

class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

it works as it should. Now, if I try to replace the class name for any other name, it won't work anymore, as it seems to always look after HelloWorldApp. I made sure the file is being saved and so, I even reopened Eclipse. Still the same error. Maybe this is a common problem, with a small work-around?

Thanks


edit: I see what you guys mean, but why does it work when I have the file name as "Main.java" and a class name of "HelloWorldApp" ?

+6  A: 

You need to rename your .java file to match the class name.

Eclipse will rename your .java file to match your class name automatically if you use its refactoring support. Right click on the class name, hover over Refactor, and select the Rename option. Now when you rename your class, Eclipse will automatically rename your .java file to match.

rcampbell
...or select the classname (or just put cursor in it) in sourcecode and hit `Alt+Shift+R`.
BalusC
That's only necessary for public classes, though. Package-private classes (not marked either public or private) can be named anything.
Michael Myers
@mmyers - you are right, didn't notice it was default scoped. Javac should have no problem producing *FooBar.class* from *HellowWorldApp.java*. I'm not sure why it wouldn't work; I'm able to change (default-scoped) class names at will and they run fine in STS 2.3.0.
rcampbell
+2  A: 

This is how Java works. Class must have the same name as the file. So the filename for the class MyApp, must be MyApp.java

crunchdog
+1  A: 

Rename main as HelloWorldApp so that your app becomes HelloWorldApp.java.

Warrior
I see your point, but if I keep the current file name (Main.java), it will work with a class name of HelloWorldApp!
devoured elysium
A: 

When changing the name of your class use the REFACTOR option - If you try to edit the name manually yourself the Eclipse Project loses track of your objects.

MikeC
I don't think that is the problem. Look in the right corner, you'll see it is updating correctly my class outline.
devoured elysium
Do you have your CLASSPATH set up correctly for Java?
MikeC
Don't know :S..
devoured elysium
Looking at the tab document - it reads "Main.java" If you had used Refactor properly it should be reading "HelloWfor.java"
MikeC