aspose file tools*
The moose likes Java in General and the fly likes How to write specific method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to write specific method" Watch "How to write specific method" New topic
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: 1667
    
    7

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: 36599
    
  16
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: 4246
    
    7

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)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to write specific method
 
Similar Threads
Generic wildcards
Why can only "real" dog bark?
Generics Doubt in for loop
Object behaviour.
"T extends Animal" VS "? extends Animal"