• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem in my First Generic program  RSS feed

 
MrKamal Joshi
Greenhorn
Posts: 24
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Compiling results in an error
incompatible types
found : T
required: T
this.t=t;
^
Please Explain
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you have a <T> at the front of your constructor? Try deleting that, and I suspect it will work.

What I think is happening here is that the <T> there is being used to define a generic method. This is separate from the T defining the generic class. So you've actually got two different Ts meaning different things, which leads to a conflict. On line 6 you're trying to assign from one to the other.
 
MrKamal Joshi
Greenhorn
Posts: 24
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah,It works when i remove <T> in front of the constructor.Thanks
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew is spot-on.
 
MrKamal Joshi
Greenhorn
Posts: 24
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:Why do you have a <T> at the front of your constructor? Try deleting that, and I suspect it will work.

What I think is happening here is that the <T> there is being used to define a generic method. This is separate from the T defining the generic class. So you've actually got two different Ts meaning different things, which leads to a conflict. On line 6 you're trying to assign from one to the other.

So it means that if i have a Generic class class Element<T,S> and i declare 3 constructors <T>Element(){}<S>Element(int a,int b){}<T,S>Element(int a,int b,int c){} then all <T> will be different?
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, that's exactly the equivalent to:

Which is better, because you avoid the possible confusion.
 
MrKamal Joshi
Greenhorn
Posts: 24
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!