aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes non-static class T cannot be referenced from a static context Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "non-static class T cannot be referenced from a static context" Watch "non-static class T cannot be referenced from a static context" New topic
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: 18

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
 
jQuery in Action, 2nd edition
 
subject: non-static class T cannot be referenced from a static context