Search code examples
javavariablesstaticsuper

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;
}

Solution

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