• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why can't we declare an outer class as static in java  RSS feed

 
javal learnerj
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why can't we declare an outer class as static in java
 
Knute Snortum
Sheriff
Posts: 4279
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the answer may be along these lines: just what would that make an outer class that is different without static?  And since it doesn't change anything, why allow it?
 
O Shea
Ranch Hand
Posts: 196
3
Java MySQL Database Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What I think is that if we make top level class as static then for every object we make of that class, each object is created at class level, i.e, for every object there is only 1 copy created. Now suppose there are 3 objects of that static class. So suppose if object 3 makes any change on the data members of that class, then that change also gets reflected for object 1 as well as object 2 of that class. That's why we can't make top level class as static.

Example:



If java allows top level class as static then we have output as 300 300 300 since for each object only 1 copy created hence changes made by any object gets reflected for each object.
That's why we can't make top level class as static.
 
Junilu Lacar
Sheriff
Posts: 11493
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Knute alluded to, it has to do with semantics. For inner classes, the semantics of static vs non-static are defined in the JLS: https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.3

Given the semantics of static vs non-static inner classes defined by the JLS, these keywords affect the scope and lifetime of instances of those classes relative to their enclosing class. On the other hand, a top-level class by definition does not have an enclosing class; its "enclosure" is the package where it is declared. As such, the static keyword provides no meaningful semantics with regard to scope and lifetime.
 
Campbell Ritchie
Marshal
Posts: 56545
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:. . . the static keyword provides no meaningful semantics with regard to scope and lifetime.
I think you can go further and say that calling a top‑level class static entails misleading semantics. Something declared static is a static member or part of something else (an enclosing class). But a top‑level class doesn't have an enclosing class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!