Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics: non-static type variable T cannot be referenced from a static context

Tags:

java

generics

interface A<T> {

    interface B {
       // Results in non-static type variable T cannot
       // be referenced from a static context
       T foo(); 
    }

}

Is there anyway round this? Why is T seen as static when referenced from A.B?

like image 301
auser Avatar asked Jun 09 '12 18:06

auser


People also ask

How do you fix non static method Cannot be referenced from a static context?

There is one simple way of solving the non-static variable cannot be referenced from a static context error. In the above code, we have to 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 non static variable Cannot be referenced from a static context in Java?

And if no class instance is created, the non-static variable is never initialized and there is no value to reference. For the same reasons, a non-static method cannot be referenced from a static context, either, as the compiler cannot tell which particular object the non-static member belongs to.

Can you access non static variable in static context?

Of course, they can but the opposite is not true i.e. you cannot access 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.

How do you assign a static variable to a non static variable in Java?

You cannot assign the result of a non-static method to a static variable. Instead, you would need to convert the getIPZip method to be a static method of your MyProps class, then you could assign its result to yor IPZip variable like this.


1 Answers

All member fields of an interface are by default public, static and final.

Since inner interface is static by default, you can't refer to T from static fields or methods.

Because T is actually associated with an instance of a class, if it were associated with a static field or method which is associated with class then it wouldn't make any sense

like image 78
jmj Avatar answered Sep 20 '22 19:09

jmj