File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to write specific method" Watch "How to write specific method" New topic

How to write specific method

Alek Zander

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.

Jelle Klap

Joined: Mar 10, 2008
Posts: 1951

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

Joined: Oct 13, 2005
Posts: 46326
And welcome to the Ranch
Alek Zander

Joined: May 09, 2011
Posts: 2

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

Joined: Apr 06, 2010
Posts: 4543

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)
I agree. Here's the link:
subject: How to write specific method
It's not a secret anymore!