1

In the code of a legacy application I just came across a class file that contained inner classes, but those inner classes where not defined within the class body but after the closing bracket of the class definition.

It looked silike this:

MyClass.java

public class MyClass {

    // class body

}

class DataStructure1 {

    String field1;

    Integer field2;

}

class DataStructure2 {

    Date field3;

    String field4;

}

Obviously the compiler does not complain, but I was quite irritated as I've never seen something like this before.

  • Are this valid inner classes?
  • Is there any difference to classes defined within the body (except from indentation)?
Markus Mitterauer
  • 1,560
  • 1
  • 14
  • 28
  • [Read the spec](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.1.3): "An inner class is a nested class that is not explicitly or implicitly declared static.", and "A nested class is any class whose declaration occurs within the body of another class or interface.". They're not inside the body of another class, so they're not inner classes. – Andy Turner Sep 12 '16 at 12:09
  • It's always easy to read something if one know's what to look for. ;-) Thanks for the link. – Markus Mitterauer Sep 12 '16 at 12:15
  • Before there was inner classes there was package local classes. This was available from Java 1.0. – Peter Lawrey Sep 12 '16 at 12:23
  • @PeterLawrey I'm aware of the (non-) modifier for "package private" classes. What I was not aware of, is the possibility to declare more than one class in a single class-file. – Markus Mitterauer Sep 12 '16 at 12:27
  • The only limitation is at most one top level public class. – Peter Lawrey Sep 12 '16 at 12:40

1 Answers1

3

These aren't inner classes at all, as far as I know, but rather two other package private classes which happened to be in the same source file. It is perfectly acceptable to have more than one class definition in a given .java file.

Inner classes, as the name implies, have to be defined inside a containing outer class. That is not the case here.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360