| Author |
More than one class in a file, compile one class - all get compiled
|
Angus Comber
Ranch Hand
Joined: Jul 16, 2011
Posts: 88
|
|
If I have 2 classes in a file named Apple.java - classes Apple and Orange. Apple contains main function. I use javac Apple.java - I notice this outputs Apple.class AND Orangle.class.
What are the rules? Is this a convenience to save have to compile each class?
Angus
|
 |
Marcin Kwiatkowski
Ranch Hand
Joined: Aug 06, 2007
Posts: 32
|
|
|
You're compiling files not classes. Using your example, javac Apple.java compiles Apple.java file not Apple class.
|
 |
Angus Comber
Ranch Hand
Joined: Jul 16, 2011
Posts: 88
|
|
Yes I worked it out in my head shortly after posting.
Just confusion I suppose between javac which takes a file and java which takes a classname.
Got it now.
|
 |
Angus Comber
Ranch Hand
Joined: Jul 16, 2011
Posts: 88
|
|
But then there is more to this. Because if I have this source:
public class MyFirstClass
{
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
And save it to a file called anything.java then if I javac anything.java I get error:
javac anything.java
anything.java:1: class MyFirstClass is public, should be declared in a file name
d MyFirstClass.java
public class MyFirstClass
^
1 error
So is the rule that the file must be named the name of the class containing the main function?
|
 |
Jacek Garlinski
Greenhorn
Joined: Aug 08, 2011
Posts: 8
|
|
The rule is:
if you've got a public class in a file, then file name must be the same as class name.
if all classes in file are with default access modifier, then name of file is up to you.
|
Please correct my English.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
I think you mean public class, but for the rest you're right.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32674
|
|
Jacek Garlinski wrote: . . .
if you've got a public function in a file, . . . .
You mean public top-level class. I presume.
|
 |
Jacek Garlinski
Greenhorn
Joined: Aug 08, 2011
Posts: 8
|
|
Campbell Ritchie wrote:
Jacek Garlinski wrote: . . .
if you've got a public function in a file, . . . .
You mean public top-level class. I presume.
Rob Spoor wrote:I think you mean public class, but for the rest you're right.
You all are right ;)
|
 |
 |
|
|
subject: More than one class in a file, compile one class - all get compiled
|
|
|