| Author |
How to write specific method
|
Alek Zander
Greenhorn
Joined: May 09, 2011
Posts: 2
|
|
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
Joined: Mar 10, 2008
Posts: 1409
|
|
|
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?
|
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
And welcome to the Ranch
|
 |
Alek Zander
Greenhorn
Joined: May 09, 2011
Posts: 2
|
|
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
Joined: Apr 06, 2010
Posts: 3795
|
|
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)
|
 |
 |
|
|
subject: How to write specific method
|
|
|