Multiple Java classes in one file

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?


Imprint

This is one of about 5000 posts on Rubénerd. View the home page for the latest, or related posts also tagged with:

If you liked this post, feel free to buy me a coffee, leave me a comment on Twitter, or email me at weblog2017@rubenschade.com. Thanks :).