Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Statics in non-static methods, constructors, inner-class et al

 
Santiago Bravo
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I was trying some code on inner classes. It mentions that static variables can only be declared in static classes or top level classes.

I was just wondering, where else can static variables and methods be declared? Of course they are allowed in the class code and static methods.
But cannont be declared in methods, construcors, non-static inner classes and anonymous classes.

Is this true and are there any exceptions?



Thanks
 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create static variables or fields inside top level classes and static inner classes only. However you can create static constants i.e. final static fields inside other inner classes and interfaces...
 
Santiago Bravo
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ankit,

Yes, interface variables are implicitly public static and final.

Originally posted by Ankit Garg:
However you can create static constants i.e. final static fields inside other inner classes and interfaces...



If I try the following:



I get a compiler error as static fields can only be declared in static or top level classes.

But if I change LINE1 to

then this works - even in anonymous inner classes.

Why is this the case?


Thanks
 
Harvinder Thakur
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Santiago,

As per the JLS Section 8.1.2 inner classes can have compile time constants. An anonymous inner class is an inner class.

class outerX {
class innerX {
static final int i = 1;//is a compile time constant
}
}

Moreover, JLS section 8.5.2 says that the static keyword has the effect of saying that the member is not an inner class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic