wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Java Generics: what is the difference between Class<T> and T? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java Generics: what is the difference between Class&lt;T&gt; and T?" Watch "Java Generics: what is the difference between Class&lt;T&gt; and T?" New topic
Author

Java Generics: what is the difference between Class&lt;T&gt; and T?

Elia Bolg
Greenhorn

Joined: Jul 08, 2008
Posts: 9
the following code was auto generated by Netbeans 7.3:

the abstract class:



extending the absrtact class:


why the following is not equivalent?:

my modified abstract class:
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

In your first example, entityClass is of type Class<T>, while in your second example, it is of type T.

Obviously, Class<T> and T are not the same type, so the examples are not equivalent. Why would you expect these to be equivalent?

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Elia Bolg
Greenhorn

Joined: Jul 08, 2008
Posts: 9
I was under the impression that when you extend the abstract class, you provide the type T (Config as in my example) so in turn the entityClass would be : private Config entityClass; I'm not getting the Class<T> in this case.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Elia Bolg wrote:I was under the impression that when you extend the abstract class, you provide the type T (Config as in my example)


That's one way to do it, yes.

so in turn the entityClass would be : private Config entityClass; I'm not getting the Class<T> in this case.


Forget about extending. And mostly forget about generics for a minute. Just think about what Class<T> vs. T means.

Class<T> means java.lang.Class, where the Class object is the one representing the class T. It might be Class<String> for the String class, or class<com.mypackage.MyFooBar> for the MyFooBar class. But it's always java.lang.class.

T, on the other hand, is whatever class you want it to be. It might be String, or it might be comp.mypakcage.MyFooBar.

Now consider what you can do with a Class object vs. what you can do with a String or MyFooBar object. Consider what the difference is between have a variable Class x; and [b]MyFooBar x;[/t]

As to why that class is using Class<T> rather than just T, you'd have to look at the rest of the class and see how it uses that variable.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Java Generics: what is the difference between Class&lt;T&gt; and T?