Multiple Java classes in one file

Software

Classic Java logo

I got so much helpful feedback from friendly people here with my last Java question I thought I'd try again with another problem that's been gnawing at me for a few days. It's probably just a matter of scope, but I want to be sure!

Say for example I have a very basic Train class and within it I have Carriage objects. In this example the private Carriage class is within the class Train:

public class Train {
  Carriage[] carriages = new Carriage[10];
  public Train() {
    // constructor stuff
  }
  private class Carriage {
    public Carriage() {
      // constructor stuff
    }
  }
}

In this version Carriage is within the same file, but is a different class. This also compiles, but if I try to append a private keyword Java throws a "modifier not allowed here" error.

public class Train {
  Carriage[] carriages = new Carriage[10];
  public Train() {
    // constructor stuff
  }
}
class Carriage {
  public Carriage() {
    // constructor stuff
  }
}

Basically I need to know what the functional difference is between the two. Both compile and can be used; on my machine here I added a bunch of toString() methods and fleshed out their constructors and got identical output with each version. Is it simply a matter of scope? Is one approach more acceptable or preferred?

Author bio and support

Me!

Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.