Tom
Tom

Reputation: 3637

Cannot make a static reference to the non-static field... but I am not making a static reference

I am quite confused as how/why this could be a problem:

public static long someMethod
{
  long local_temp_var = PackageInfo.lastUpdateTime;    
}

gives error message

Cannot make a static reference to the non-static field PackageInfo.lastUpdateTime

The error messafe claims I am trying to make a static reference? I don't really believe I am. Yes, it is in a static/class method, but the variable is a local one.

Upvotes: 0

Views: 163

Answers (4)

Christopher Rucinski
Christopher Rucinski

Reputation: 4867

Ok. the problem is that the variable lastUpdateTime in PackageInfo IS NOT static! But you are calling it as if it was.

JavaDoc of PackageInfo

You have to create a new instance of PackageInfo aka...

PackageInfo info = new PackageInfo();

then you can do....

long local_temp_var = info.lastUpdateTime; // Take note the "info" variable from above

Upvotes: 3

ppeterka
ppeterka

Reputation: 20736

This is a static method

//notice the () brackets you miss in your question.
public static long someMethod() {...}

All references therein are considered static.

but the variable is a local one.

Yes, a local instance variable. Not static -- this is the cause of the error you see.

Also, the naming seems to be off. PackageInfo seems to be your local variable, but this is not how we name those: is should start with a lowercase letter.

A line in Java that reads PackageInfo.something sends the message: "PackageInfo is a class, and we access its static field named something". If PackageInfo is not a class, but an instance of a class, this sends a misleading message - which kills maintainability.

Upvotes: 1

Aashray
Aashray

Reputation: 2763

If in the declaration you have mentioned:

static long lastUpdateTime;

Then it would fine.

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122026

You cannot access non static fields in the static context.

Since the field lastUpdateTime is non static,it is saying to make it static or don't use here.

Upvotes: 2

Related Questions