I got a very weird compile-time error:
class Super {
Super(int[] array) {
}
}
class Sub extends Super {
private final int number = 1;
Sub() {
super(new int[] { number }); //error
}
}
The error I get is
Cannot access field from static context
My question
Where is the static context? It doesn't seem as if static would even play a role here.
I stumbled across this attempting to answer someone else's question; found the error I got baffling. Can someone explain where the static context is?
There is one simple way of solving the non-static variable cannot be referenced from a static context error. Address the non-static variable with the object name. In a simple way, we have to create an object of the class to refer to a non-static variable from a static context.
Why does this error occur? For the non-static variable, there is a need for an object instance to call the variables. We can also create multiple objects by assigning different values for that non-static variable. So, different objects may have different values for the same variable.
Of course, they can, but the opposite is not true, i.e. you cannot obtain a non-static member from a static context, i.e. static method. The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs to.
A non-static method is dependent on the object. It is recognized by the program once the object is created. But a static method can be called before the object creation. Hence you cannot make the reference.
Your field number
should be static, so that you can use it in constructor call. Otherwise you'll get cannot reference number before supertype constructor has been called
because the field is not accessible before you call the constructor of the parent class.
So your code should look like:
class Super {
Super(int[] array) {
}
}
class Sub extends Super {
private static final int number = 1;
Sub() {
super(new int[] { number }); //error
}
}
From JLS 8.8.7
An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use
this
orsuper
in any expression; otherwise, a compile-time error occurs.
At the time of the super
call an instance of Sub
will not yet exist
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With