Static Access Discrepancy?

P

Paul Carey

Hi
I just noticed the following when studying for the scjp. Does anyone
know if there's any reason for the compiler errors generated by the
commented line below as to me it doesn't seem consistent with the
other ways of accessing static variables and methods.
Thanks
Paul

public class StaticAccess
{
static int i = 0;

static int method()
{
return 5;
}

static class StaticNested
{
int nestedMethod()
{
return 10;
}
}

void testAccess()
{
int a = StaticAccess.i;
int b = this.i;

int c = StaticAccess.method();
int d = this.method();

StaticNested sna = new StaticAccess.StaticNested();
// StaticNested snb = new this.StaticNested();

StaticNested snc = new StaticNested();
}
}
 
J

Jon Skeet

Paul Carey said:
I just noticed the following when studying for the scjp. Does anyone
know if there's any reason for the compiler errors generated by the
commented line below as to me it doesn't seem consistent with the
other ways of accessing static variables and methods.

Indeed, it's not. Out of all the various bits of horrible syntax for
nested classes, this is the one bit which is not only good, but better
than the rest of Java.

I would recommend never accessing static members with a reference type
expression - it only leads to misleading code such as
Thread.currentThread.sleep(...).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top