Why is the following code ok, but as soon as T is added to Main as a generic, it throws the following error?
'Main.this' cannot be referenced from a static context
//public class Main<T> { - uncomment this for the error to appear
public class Main {
public static void main(String[] args) {
new Main();
}
class TestNonStatic {}
private static class TestStatic {
public TestStatic(TestNonStatic nonStatic) { //this is the line that fails
}
}
}
I went through generics restrictions but I don't get it why this results into an error. I also went through a lot of similar questions but I don't understand why adding the generic would change the situation.
Therefore, this issue can be solved by addressing the variables with the object names. In short, we always need to create an object in order to refer to a non-static variable from a static context. Whenever a new instance is created, a new copy of all the non-static variables and methods are created.
But static contexts(methods and blocks) doesn't have any instance they belong to the class. In a simple sense, to use “this” the method should be invoked by an object, which is not always necessary with static methods. Therefore, you cannot use this keyword from a static method.
A non-static method in Java can access static methods and variables as follows: A non-static method can access any static method without creating an instance of the class. A non-static method can access any static variable without creating an instance of the class because the static variable belongs to the class.
i.e. referring a variable using static reference implies to referring using the class name. But, to access instance variables it is a must to create an object, these are not available in the memory, before instantiation. Therefore, you cannot make static reference to non-static fields(variables) in Java.
Your TestNonStatic
has an implicit generic which you have to specify whether it is a raw type
public TestStatic(Main.TestNonStatic nonStatic) {
or a generic type
public TestStatic(Main<String>.TestNonStatic nonStatic) {
or using a non-static class
private class TestStatic {
public TestStatic(/*Main<T>.*/TestNonStatic nonStatic) {
It won't implicitly assume the following, as the class is static
public TestStatic(Main<T>.TestNonStatic nonStatic) {
Why doesn't have some default behaviour, possibly because this might lead to even more obscure error messages ;)
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