1

As far as I know the differences between regular class and anonymous class are:

  • Anonymous class can't implement multiple interfaces whereas regular class can.
  • Anonymous class can't extend class and implement interface at the same time whereas regular class can.
  • Anonymous class doesn't have a name while regular class has.
  • Anonymous class can't define a constructor because anonymous class doesn't have a name whereas regular class can.

Is there a reason why these rules are implemented in anonymous class?

  • static fields of anonymous class must be constant.
  • an interface can't be a member of anonymous class.
  • static block/initializer can't be used in anonymous class.
Blue
  • 23
  • 5
  • 'Anonymous class doesn't have a name' is a tautology, and there is no syntax to support the remainder of your first four points. – user207421 Apr 16 '18 at 06:13

1 Answers1

1

Because JLS 15.9.5. Anonymous Class Declarations says:

An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1).

And JLS 8.1.3. Inner Classes and Enclosing Instances says:

It is a compile-time error if an inner class declares a static initializer (§8.7).

It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable (§4.12.4).

Note that interfaces are implicitly static.

See also question:

Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Thanks for pointing this out! I don't read JLS documentation that much because it's too technical and the documentation itself is too intimidating. – Blue Apr 16 '18 at 07:27