| Author |
non-static class T cannot be referenced from a static context
|
Faber Siagian
Ranch Hand
Joined: Jul 08, 2008
Posts: 52
|
|
I have created a program like shown below : And the error : non-static class T cannot be referenced from a static context Would someone explain to me aboout the error ?
|
Sun Certified Programmer for the Java 2 Platform, Standard Edition 5.0 (88 %)
|
 |
Raphael Rabadan
Ranch Hand
Joined: Jul 05, 2008
Posts: 141
|
|
Looks like someone is doing whizlabs :-D Ok, let's think. T is a type defined by a instance when you create it. Like Class<Object> c = new Class<Object>(); But using it in a static method, what would be this T if you had no instance? Or if you had two instances? You can't define it because it's defined when you instantiate a class, and you won't do it using static members. You can only use a generic type created in a method for static methods.
|
SCJP Java 6 (98%) - Story, SCJA (88%) - Story
|
 |
Sergiy Subota
Greenhorn
Joined: Mar 05, 2013
Posts: 1
|
|
Raphael Rabadan wrote:Looks like someone is doing whizlabs :-D
Ok, let's think.
T is a type defined by a instance when you create it. Like Class<Object> c = new Class<Object>();
But using it in a static method, what would be this T if you had no instance? Or if you had two instances? You can't define it because it's defined when you instantiate a class, and you won't do it using static members.
You can only use a generic type created in a method for static methods.
There a special kind of logic in Java, I guess...
c++ gets it just fine - it actually compiles a version of generic class
for every template parameter actually used.
Each class has it's own static variables.
try compiling this test.cpp:
|
 |
Bhavesh Saraswat
Greenhorn
Joined: Jan 20, 2013
Posts: 17
|
|
|
well I think generic class converts to a specific type when its object is created with new . Before creating a object it is of no type. so static variables can not use a generic type.
|
OCPJP SE6
|
 |
 |
|
|
subject: non-static class T cannot be referenced from a static context
|
|
|