Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to write specific method

 
Alek Zander
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have 3 classes:

abstract class Animal{}
class Dog extends Animal{}
class Mouse extends Animal{}

How to write method that can as a parameter get Dog and Maouse without Animal?

I tried:

public <T extends Animal> void doSomething(T param) {}

but as a param instead of Dog and Mouse I can also set Animal.

Thanks
alekzander
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Animal is the only shared type in both type hierarchies, aside from Object, so in the current hierarchy setup it's you're only reasonable option if you want a single method that accepts both types. You could make the Animal class abstract to prevent an instances of Animal being created and passed instead of instance of a sub-type of Animal. Though that wouldn't restrict the method from accepting sub-types other then Dog and Mouse. Maybe it's an option to introduce an interface that both Dog and Mouse implement and base the method on that type instead?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49411
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
Alek Zander
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome!!

I forgot to write that my Animal class is abstract and instead of this i can set an abstract class as a param to my method.
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The other alternative is to use method overloading, so you actually have two separate methods. You can then have them delegate to a common private method to avoid code duplication. For example:

The best solution is likely to depend on why you want to be able to pass a Dog or a Mouse but not an Animal.

(Edit: posted before I saw your followup. If you can just pass the abstract Animal, that's simpler and better)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic