• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics question  RSS feed

 
Dirk Lucas
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.

I am doing some study work.

I do not understand the following --> question is red coloured. Can anyone tell me why that method does not have to be generic? It takes a generic type parameter so...why o why not?

 
Campbell Ritchie
Marshal
Posts: 56585
172
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dirk Lucas wrote:. . . question is red coloured.  . . .
No, it isn't. The colour tags don't work inside the code tags, so I shall remove them. You mean that the question appears on line 13.

It is only necessary to make a method generic if it doesn't have any generic information from the object. The formal type parameter E is part of the definition of the object, so it is available to all instances of your class.
VerzamelingHuisdier<Dog> kennel = new VerzamelingHuisdier<>();
VerzamelingHuisdier<Cat> clowder = new VerzamelingHuisdier<>();

All the dogs in the kennel know they are dogs and all the cats in the clowder know they are cats. So there is no need for the method to have an <E> in its declaration.
But what if the method were static? It would not know whether it is dealing with dogs or cats, so you would have to make it generic.
 
Dirk Lucas
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very clear answer!

I noticed making it red didnt work, but could not find a button to edit my message.

Thanks again! Saved me a headache

 
Campbell Ritchie
Marshal
Posts: 56585
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There isn't an edit button; use the preview option underneath the pane where you write the original text.

And . . . “that's a pleasure
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!