Question:
Is it necessary to define a public java class in a separate file?WHY?
anonymous
2010-02-02 04:10:17 UTC
If the class is:
public class ABC{
}

is it necessary to define this class in a separate file named ABC.java?
WHY?
Five answers:
Frecklefoot
2010-02-02 04:16:00 UTC
That's just the way Java works. All class files have to go in files with the class name. The exception to this are inner classes, like this:



public class Foo {

...

private class Bar {

...

}

}



which reside in the same file as the "outer" class. You might find better answers at JavaRanch (http://www.coderanch.com/forums). HTH
anonymous
2010-02-02 04:18:33 UTC
Classes are compilation units for Java programs. You can nest classes:



public class ABC {

public class DEF extends ABC{}

}



but the top level class really should be in it's own file. You'll notice when you compile that that the inner class is extracted and the byte code stored in a seperate .class file.



Java still supports multiple classes in a file but it's only for backwards compatability (to Java 1.0!!!)
Kardinal
2010-02-02 04:26:03 UTC
Very simply put, it's because if you have all classes in one file, each time you make a minor change in any of those classes you'll have to recompile the whole program. By putting each class in a different file, when you make a change in one class only that file is recompiled (wich is faster, specially on large programs).

There are more reasons than that, but that is one of the main reasons for it.
anonymous
2016-05-26 08:04:55 UTC
I suspect you've not copied and pasted that exactly. Helloworld and helloworld are different identifiers in java because the first letter, the H and the h, are considered different. Rename you file to Helloworld.java or your class to helloworld.java.
faizan_akbar2001
2010-02-02 04:14:36 UTC
no u dont have to define a class again in seperate file u can just extend it like...



public class EFG extends ABC

{



}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...