Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

non-static class T cannot be referenced from a static context

 
Faber Siagian
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
Raphael Rabadan
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sergiy Subota
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18
Java Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic