M.hossein
M.hossein

Reputation: 11

Error: Non-static variable super cannot be referenced from a static context >>but i use static keyword

How can i refers to "a1" from superclass (class "aa") with "super" keyword

class aa {
protected static int a1 = 2;
}

public class bb extendeds aa {
static int a1 = 3;
public static int s = super.a1;
}

Upvotes: 0

Views: 305

Answers (2)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

The static members of a class belong to a class and not to a particular instance.

When you invoke super.member you are trying to access the member of the current instance inherited from the parent class. It is done so because the same member might be shadowed in the child class, so super will refer to the member in the parent class.

So in a static context it is ambiguous that from which instance the member is going to be initialised with a value. In fact static members can be accessed when no instances exist. So the usage of super in a static context (method or in your case a field) is not possible and the compiler throws an error.

Furthermore the static fields are initialised when the class is loaded at which point no instance variables are initialised. So initialising with super.member makes no sense.

From JLS:

The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.

You need to modify your code to:

public class bb extendeds aa {
   static int a1 = 3;
   public static int s = aa.a1; //a1 belongs to class aa not to an instance
}

Upvotes: 1

Nexevis
Nexevis

Reputation: 4667

If you really want to use super instead of just doing aa.a1, you can technically do this in the constructor without error and only get a warning:

public static int s;

public bb(){
    this.s = super.a1;
}

Test Run:

aa a = new aa();
bb b = new bb();
System.out.println(a.a1);
System.out.println(b.s);

Output:

2

2

I really do not recommend doing this and try to avoid using static with objects or just use static like a static field if you really do need one.

Upvotes: 0

Related Questions