• Post Reply Bookmark Topic Watch Topic
  • New Topic

generics with polymorphism  RSS feed

 
Prash Negu
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am trying to use Java Generics in achieving polymorphism and couldnt succeed. I know generics is just make templates and type saftey, but still couldnt convince myslef about comilation error. What is wrong with "hee" method here?




Thanks,
Prashant
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Child.test requires a B but the obj can also be an A, or a C (if C extends A directly or indirectly).

You can fix this three ways:
1) remove the <T extends A> in method hee, and use B as the parameter type
2) replace the Child inside hee with a Parent<T>
3) make Child generic as well: class Child<T1 extends A> extends Parent<T1>
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
change your code like below; as compiler tells, Child doest have test(A obj) method.
 
Prash Negu
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
None of the solution works except removing generics in "hee" method.

My intention is to NOT to write different variants of "hee" methods.
 
Prash Negu
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what I am trying to achieve. In below code, at line # 12 and 13, always "A...." will be printed. How can i make it polymorphic? That is, at line 12, it should print "A...." and at 13 it should print "B...". I dont want to write another method that takes B as input parameter.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!