Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

More than one class in a file, compile one class - all get compiled

 
Angus Comber
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're compiling files not classes. Using your example, javac Apple.java compiles Apple.java file not Apple class.
 
Angus Comber
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you mean public class, but for the rest you're right.
 
Campbell Ritchie
Sheriff
Posts: 48402
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jacek Garlinski wrote: . . .
if you've got a public function in a file, . . . .
You mean public top-level class. I presume.
 
Jacek Garlinski
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ;)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic