I have two objects which use really similar methods, save for one line. For example:
public class Cat extends Animal
public class Dog extends Animal
And they both use a breed method in the abstract class Animal. One calls new Dog(), and the other new Cat(). Right now I just have it declared as abstract public void breed(); in Animal, but is there a way I can generalize it so I don’t have to make it an abstract method to be overridden?
There are many ways to do this, assuming by
breedyou mean “create children of me.”Reflection
First is to use reflection. If you have a no-args constructor for your classes, this is as easy as calling Class.newInstance:
If you don’t have a no-args constructor in all your subclasses, you’ll have to have a uniform constructor across all your subclasses. For example, if you have
Cat(int, String)andDog(int, String), then you need to get the constructor viaClass.getConstructorand invokenewInstanceon that:intandStringhere may be age and name, for example. This is how you do this with reflection.Providers
Another way is to use this simple interface:
Then have your abstract class take an instance of this in its constructor:
Then your subclasses will pass a
Provider<Animal>to the superclass which will create new instances of the subclass:Do the same for other subclasses as well.
Note: if by
breedyou mean “get the type of me,” then you should edit your question to say so. If this is what you meant, then this is a viable solution:I recommend following the
get/setconventions for data container methods. Java has bean classes designed to handle these naming conventions, and it’s more or less a standard across many platforms. For your subclasses: