aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Statics in non-static methods, constructors, inner-class et al Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Statics in non-static methods, constructors, inner-class et al" Watch "Statics in non-static methods, constructors, inner-class et al" New topic
Author

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

Santiago Bravo
Ranch Hand

Joined: Jul 25, 2008
Posts: 226
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


Santiago
My Path to SCJP Certification My Path to SCWCD Certification
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9313
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Santiago Bravo
Ranch Hand

Joined: Jul 25, 2008
Posts: 226
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

Joined: Jun 10, 2008
Posts: 231
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.


thanks
Harvinder
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Statics in non-static methods, constructors, inner-class et al