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)?
5
  • Read the spec: "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. Commented Sep 12, 2016 at 12:09
  • It's always easy to read something if one know's what to look for. ;-) Thanks for the link. Commented Sep 12, 2016 at 12:15
  • Before there was inner classes there was package local classes. This was available from Java 1.0. Commented Sep 12, 2016 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. Commented Sep 12, 2016 at 12:27
  • The only limitation is at most one top level public class. Commented Sep 12, 2016 at 12:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

How did you even add an answer to an already duplicated question?
@Codebender Brilliant question. I think Andy marked duplicate before I posted, but I actually started writing before he marked duplicate. So it seems that as long as you have started an answer the SO engine will let you get the answer in.
@TimBiegeleisen that is the behaviour I have read should be the case, but I have found the button gets greyed out if the question is marked duplicate, even if I've started writing.
A case of "ACID vs. eventual consistency"?
@MarkusMitterauer probably something like that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.