• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to extend from a generic class?  RSS feed

 
Grary Stimon
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm not very comfortable with generics and I can't seem to reason myself through the following challenge. Can anyone help?

Say abstract class Tomato<H extends Stemmed> has two protected abstract methods: Type<H> getType() and void dispatch(H someArg). How do I subclass Tomato so that I can implement the two abstract methods to become parameterized with some subtype of Stemmed? I want to subclass Tomato in a variety of ways, such that the two abstract methods involve parameters that subtype Stemmed. As it stands now, the compiler insists that only H can be used in my method implementations, not subtypes of H.

Thanks for any help,

Grary
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all I find Tomato a weird name for a abstract class. I find that more a name for a concrete class. I think Plant or Vegetable a better name.
Second why use an abstract class with only abstract methods? Why not use an interface?

Something like this:


 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I think Fruit would be a better abstract class for Tomato. And instead of GreenTomato color should be a property of the abstract Fruit class. But I suppose that is a bit off topic.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I totally agree with you but I couldn't think of a good example to extend a Tomato
 
Grary Stimon
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Wouter,

Thanks so much for your thoughtful reply.

When I re-attempt my challenge with your proposed implementation, it fails with the message:
"Bound mismatch. The type T is not a valid substitute for the bounded parameter <T extends Stemmed> of the type Tomato<T>"

Please note that the abstract class would be more like the following, where Type<T> is a nested static class



Any further thoughts would be greatly appreciated.

Best,

Grar
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It took me a while to figure this one out. You're using eclipse aren't you? Because that error you posted is from eclipse not the java compiler and because I write my code in gedit I got a different error.
I assume that you're trying something like this:

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!