I have a parent class:
public class Animal {
public Animal(String name, AnimalTypeEnum type) {
}
}
I have lots (in the case that has caused me to make this over 30) children:
public class Dog extends Animal {
public Dog(String name, AnimalTypeEnum type) {
super(name,type);
}
}
public class Cat extends Animal {
public Cat(String name, AnimalTypeEnum type) {
super(name,type);
}
}
The objects are constructed from many different places in the project (loaded on start up, created at various times in runtime. To "create" an object, I currently use this function (over 30 subclasses in the project, not just 2):
public static Animal create(String name, AnimalTypeEnum type) {
switch(type) {
case DOG:
return new Dog(name, type);
case CAT:
return new Cat(name, type);
}
}
It is important to note that none of the subclasses have any difference in parameters. The reason I'm using subclasses is because they have one or two functions that are overriden.
Say I now wanted to add a parameter for all subclasses, I'd need to:
Add the parameter to the Animal constructor
Add the parameter to the subclass constructors
Add the parameter to the create() function
(also change the parameter wherever the create() function is being called)
Ideally, I'd like to eliminate changing the subclass parameters (none of the subclasses have different parameters) and the create() function from the above process. But if that isn't possible, I'd like to find a better alternative to the create() function. The best solution I've thought of (psuedocode) is:
public Animal(String name, AnimalTypeEnum type) {
if (type == CAT) this.subclass(Cat);
if (type == DOG) this.subclass(Dog);
}
I think the above goes against the principle of class inheritance so I want to be clear that this isn't the solution I am trying to find, just how I imagine a solution could work.
This is a rather trivial issue but I feel that bad programming practices are behind it and I would like to rectify these. My questions would be (incase I haven't properly explained my problem/reasons):
Is inheritance even the ideal way to do this?
Is it possible to eliminate the process of changing the constructor in subclasses in this situation?
Is there anything I can do to remove the create() function, and assign the subclass when constructing Animal?
Thank you.
I think that you wonna use the Factory Pattern, so you have any options for solve your problem #Doleron showed the first one, but you can use this too:
public interface Animal {
public String getName();
}
The implementation Dog
public class Dog implements Animal{
private String name;
public Dog(String name) {
this.name=name;
}
#Override
public String getName() {
return name;
}
}
Cat
public class Cat implements Animal{
private String name;
public Cat(String name) {
this.name=name;
}
#Override
public String getName() {
return name;
}
}
Factory
public class AnimalFactory {
/*
* Some people use static attributs like:
* public static final String DOG ="DOG";
*/
public static Animal creatAnimal(String animal, String name){
if("DOG".equalsIgnoreCase(animal)){
return new Dog(name);
} else if("CAT".equalsIgnoreCase(animal)){
return new Cat(name);
}
return null;
}
}
Main
public static void main(String[] args) {
Animal animal = AnimalFactory.creatAnimal("dog", "pluto");
/*
* if you use static attribut you can call this form
*/
//Animal dog = AnimalFactory.creatAnimal(AnimalFactory.DOG, "pluto");
System.out.println("Name "+animal.getName()+ " class "+animal.getClass().getSimpleName() );
animal = AnimalFactory.creatAnimal("cat", "garfield");
System.out.println("Name "+animal.getName()+ " class "+animal.getClass().getSimpleName() );
}
you can see another example here.
Since you have an enum to identify the instance type, you could avoid the create/switch/if-else approach using a polymorphic enumeration like:
public enum AnimalTypeEnum {
CAT {
public Animal create(String name) {
return new Cat(name);
}
},
DOG {
public Animal create(String name) {
return new Dog(name);
}
},
COW {
public Animal create(String name) {
return new Cow(name);
}
};
abstract Animal create(String name);
}
As everything this approach has pros and cons. Please see if it fits to your requirements.
First of all, the base class Animal should be an abstract class, because you'll never give life to an Animal object but to a more specific type of Animal, i.e Dog, Cat et cetera. In this way, all animals will have some base methods already implemented.However, if some subclass needs to inherit from another class, you should consider Animal as an Interface, because Java doesn't allow multiple inheritance.
For your second question, if I correctly understand, why can't you add a protected member to the base class Animal and initialize it in the Animal costructor? Eventually, if subclasses as a specific value for this parameter, you can set it in the subclasses costructors.
Finally for the create() function in my opinion you should consider the Abstract Factory pattern.
Related
I'm using Java 8 / Java 11. I have a type hierarchy (basically dtos or Java Beans) like
public abstract class Animal {
public abstract String getName();
public abstract int getAge();
}
And some imeplementations providing additional properties:
public class Dog extends Animal {
// implementation of abstract methods from base class animal
// additional properties
public String getSound() {
return "woof";
}
}
public class Dog extends Animal {
// implementation of abstract methods from base class animal
// additional properties
public String getSound() {
return "miaow";
}
}
public class Fish extends Animal {
// implementation of abstract methods from base class animal
// no implementaion for "getSound()"
}
Now, I'd like to process a Collection of Animals in a uniform way, e.g.
animals.forEach(x -> {
System.out.println(x.getName()); // works
System.out.println(x.getSound(); // doesn't work, as Fish is missing the method
});
I was wondering, what would be a good way to implement the "missing" methods assuming that they should return a default value like "n/a" for a String.
One obvious way would be to move all the missing methods to the base class and either declare them abstract or provide a default implementation.
But I'd like to have them more separate, i.e. making clear which properties were added for the "uniform processing".
Another way would be to introduce a helper class using instance of to determine, if the method is missing:
public class AnimalHelper {
public static String getSoundOrDefault(Animal animal) {
if (animal instanceof Dog) {
return ((Dog)animal).getSound();
}
if (animal instanceof Cat) {
return ((Cat)animal).getSound();
}
return "n/a";
}
}
which then gets called with an Animal:
System.out.println(AnimalHelper.getSoundOrDefault(animal));
This works, but the caller must now which methods to call on Animal directly and for which methods to use the helper.
Another solution, I came up with the adding an interface AnimalAdapter using the Java 8 feature of default implementation:
public interface AnimalAdapter {
default String getSoundOrDefault() {
return "n/a";
}
}
And adding it to the Animal class:
public abstract class Animal implements AnimalAdapter {
...
which results in adding the getSoundOrDefault() method in Dog and Cat, but not Fish:
public class Dog extends Animal {
...
#Override
public String getSoundOrDefault() {
return getSound();
}
}
(likewise in Cat).
Any comments on the above considerations or other ideas would be highly appreciated.
All what you have mentioned above as solutions are really good. But I take advantage to add more one solution based on polymorphism technic, and I think it's more simple and less expensive in terms of code.
Simply I'm gonna use Object.toString() method to display all needed parameters, so first of all you have to #Override toString() method as follow:
public class Dog extends Animal {
// implementation of abstract methods from base class animal
// additional properties
public String getSound() {
return "woof";
}
#Override
public String toString() {
return getName() + "\n" + getSound();
}
}
public class Fish extends Animal {
// implementation of abstract methods from base class animal
// no implementaion for "getSound()"
#Override
public String toString() {
return getName() + "\n" + "n/a";
}
}
public class Main {
public static void main(String[] args) {
Collection<Animal> animals = new ArrayList<>(2);
animals.add(new Dog());
animals.add(new Fish());
animals.forEach(System.out::println);
}
}
And here is the result:
I am exploring using the Builder design pattern to create subclasses of a parent object, based specifically on the generic type of the subclass. That sentence is kind of confusing, here is what I mean:
public class Animal(){
private String name;
private String gender;
public Animal(Builder<?> builder){
this.name = builder.name;
this.gender = builder.gender;
}
public static Builder<T extends Animal>{
private String name;
private String gender;
public Builder<T> setName(String name){
this.name = name;
return this;
}
public Builder<T> setGender(String gender){
this.gender = gender;
return this;
}
public T build(Class<T> clazz){
try {
Constructor<T> c = clazz.getDeclaredConstructor(Builder.class);
c.setAccessible(true);
return c.newInstance(this);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
}
Except, this ends up being rather error prone and "hackish". I want to be able to have one Builder that creates all the subclasses.
Question
Is there a better way to do this? Maybe the Builder design pattern is just not suited for my needs. This works, but doesn't feel right.
NOTE: The true needs of this question are not as trivial as the Animal class example. You could imagine I am trying to build a subclass to a parent class that contains many arguments. Using the builder pattern will make this a much easier instantiation and easier to extend for future subclasses.
The subclassed objects will have their own methods ONLY. No extra fields, only methods strictly defined to their type of subclass.
I.e. a Duck is a subclass of bird and it quacks. An emu is a subclass of bird, but I don't want it to quack, it will only run. But I both want them to have a name and gender.
Rather than the user specifying the Animal class, I would have each Animal subclass have its own Builder which can build that Animal.
That is:
public abstract class Animal {
protected Animal(Builder<?> builder) { ... }
public abstract static class Builder<T extends Animal> {
// setters for fields common to all animals go here
public abstract T build();
}
}
public final class Dog extends Animal {
private Dog(Builder builder) {
super(builder);
}
public static final class Builder extends Animal.Builder<Dog> {
#Override
public Dog build() {
return new Dog(this);
}
}
}
This question already has answers here:
Is this an acceptable use of instanceof?
(2 answers)
Closed 7 years ago.
I'm new to Java and struggling with a design problem. I know use of instanceof may indicate a design flaw and I understand the often given Animal/Dog/Cat classes as example, replacing bark() and meow() with makenoise() etc.
My question is, what is a sensible design if I need to call methods which do not have a corresponding method depending on the type of subclass? For example, what if I want to call a new method biteleash() if the class is a Dog but do nothing at all if it's a Cat?
I did consider having biteleash() in Animal which does nothing, and overriding it in Dog, but there are methods many like this so it seems a clunky solution. In a similar vein, what if the caller needs to do something different depending on which subclass it has hold of, eg. terminate if subclass is a Cat? Is instanceof acceptable here, or is there a better way?
public class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void makeNoise() {
System.out.println("Some noise for a generic animal!");
}
}
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
#Override
public void makeNoise() {
System.out.println("Meow");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
#Override
public void makeNoise() {
System.out.println("Woof");
}
public void biteLeash() {
System.out.println("Leash snapped!");
}
}
import java.util.Random;
public class CodeExample {
public static void main(String[] args) {
Animal animal = getSomeAnimal();
System.out.println("My pet is called " + animal.getName());
animal.makeNoise();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.biteLeash();
// do lots of other things because animal is a dog
// eg. sign up for puppy training lessons
}
}
private static Animal getSomeAnimal() {
Animal animal;
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100);
if (randomInt < 50) {
animal = new Dog("Rover");
}
else {
animal = new Cat("Tiddles");
}
return animal;
}
}
Composition will help you here, and is idiomatic in Java.
Design an interface called, say, Leashable. This is implemented by a Dog, but not a Cat.
Rather than using instanceof, you can attempt a reference cast to Leashable to see if it's implemented by your particular object.
In my opinion, you should continue in a similar vein: Build a NoisyAnimal interface too. Perhaps even just Noisy as why should noisiness be pertinent to only animals? Implementing that for a Parrot, say, will have technical challenges beyond a Cat or Dog. Good maintainable programs isolate areas of complexity and composition helps you achieve that.
You shouldn't use concrete classes. Instanceof itself isnt a problem. It exists for a reason. You should use interfaces for loose coupling i.e. your code shouldnt be dependent on concrete class implementations. I suggest you using interfaces wherever possible (i.e. IAnimal instead of Animal)
Instead of checking for Dog, you should use an interface like ILeashable (yeah a bit ridiculous for a name lol), then:
public interface ILeashable {
//add other methods which is connected to being on a leash
void biteLeash();
}
class Dog implements ILeashable {...}
Also there is no one way of doing this, there are certain patterns i.e. decorators or Dependency Inversion which might help you in this case.
Just so you know, this issue you're having is not something you'll generally be facing in the real world. If you have to have implementation-specific logic on some class that implements an interface or an abstract base class, it will usually be because at some higher level you need to get a derived property. This psuedocode to illustrate:
interface ISellable {
decimal getPrice();
}
class CaseItem : ISellable {
int numItemsInCase;
decimal pricePerUnit;
decimal getPrice() {
return numItemsInCase*pricePerUnit;
}
}
class IndividualItem : ISellable{
decimal pricePerUnit;
decimal getPrice() {
return pricePerUnit;
}
}
main() {
aCaseItem = new CaseItem { pricePerUnit = 2, numItemsInCase=5 }; //getPrice() returns 10
anIndividualItem = new IndividualItem { pricePerUnit = 5 }; //getPrice() returns 5
List<ISellable> order = new List<ISellable>();
order.Add(aCaseItem);
order.Add(anIndividualItem);
print getOrderTotal(order);
}
function getOrderTotal(List<ISellable> sellableItems) {
return sellableItems.Sum(i => i.getPrice());
}
Notice that I am using the interface to abstract away the concept of an item's price, but when I'm actually in the main method, I can easily create instances of the specific type in order to control the behaviors of the two classes.
However, when I need to get the price, I'm referencing the items as a list of ISellable, which only exposes their "getPrice()" method for my convenience.
Personally, I always believed the animal methaphor to be severely lacking. It doesn't explain this concept in a way that makes sense, and it doesn't clue you in on how to use it in the real world.
Think of it this way: What event causes the Dog to bite its leash? Or differently speaking, what is your motivation to make it perform this action?
In your example there is actually none. It just so happens that in your main method you decided to put in a check and if the animal you randomly created is a Dog, you make it do certain dog things. That's not how code in the real world works.
When you write code, you want to solve some problem. To stick to the animals example, let's pretend you write a game where you have pets that react to certain events like turning on the vacuum or getting a treat. From this sentence alone we can create a reasonable class hierarchy:
interface Animal {
void reactToVacuum();
void receiveTreat();
}
class Dog implements Animal {
public void biteLeash() {
System.out.println("Leash snapped!");
}
public void wiggleTail() {
System.out.println("Tail is wiggling!");
}
#Override
public void reactToVacuum() {
biteLeash();
}
#Override
public void receiveTreat() {
wiggleTail();
}
}
As you can see, the leash biting happens in response to an event, namely turning on the vacuum.
For a more realistic example, take Android's view hierarchy. A View is the base class for every control on the screen, e.g. a Button, an EditText and so on. View.onDraw() is defined for every view but depending on what View you have, something different will happen. EditText for example will do something like drawCursor() and drawText().
As you can see, the answer to the question "What event causes the EditText to draw the cursor" is "It needs to be drawn on the screen". No instanceof or condition checking necessary.
As in your example - some subclasses can have different methods.
This is typical scenario where you have to use instanceof.
If your subclasses are fixed then you can use animalType to avoid instanceof.
I prefer that u can use interface to check whether the feature is available with the subclass, but it is not feasible for large number of subclass dependent methods. ( solution given by user2710256).
Enum Type {
DOG,CAT ;
}
public abstract class Animal {
String name;
Type type;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void makeNoise() {
System.out.println("Some noise for a generic animal!");
}
abstract Type getType();
}
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
#Override
public void makeNoise() {
System.out.println("Meow");
}
public Type getType() {
return Type.CAT;
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
#Override
public void makeNoise() {
System.out.println("Woof");
}
public void biteLeash() {
System.out.println("Leash snapped!");
}
public Type getType(){
return Type.DOG;
}
}
import java.util.Random;
public class CodeExample {
public static void main(String[] args) {
Animal animal = getSomeAnimal();
System.out.println("My pet is called " + animal.getName());
animal.makeNoise();
switch(animal.getType())
{
case DOG:
{
Dog dog = (Dog) animal;
dog.biteLeash();
// do lots of other things because animal is a dog
// eg. sign up for puppy training lessons
}
case CAT:
{
// do cat stuff
}
default:
throw new Exception("Invalid Animal");
}
}
private static Animal getSomeAnimal() {
Animal animal;
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100);
if (randomInt < 50) {
animal = new Dog("Rover");
}
else {
animal = new Cat("Tiddles");
}
return animal;
}
}
Of course having biteleash() in a Cat doesn't make sense, for you don't walk cats on a leash. So Animal shouldn't have biteleash(). Maybe you should put a method like playWith() in an Animal, in which Dogs would biteleash(). What I'm trying to say is you probably need to be more general. You shouldn't care if it is a dog to manually call biteleash(). Adding a Ferret to your Zoo would require adding the possibility that the animal is a Ferret, since they can also biteleash().
And maybe a method shouldTerminate(), which returns true in Cats. You will probably want to terminate also on a Tortoise in a while.
Generally, People consider it bad practice, if adding a new subclass would require changes in code using this class.
If I may, this is a highly impractical way to do this, I'm not sure what you are after but instanceof is going to be tedious, what you end up with is high coupling which is a no go when doing OOD.
Here is what I'd do:
First, get rid of class Animal and make it an interface as following
public interface Animal {
public String getName();
public void makeNoise();
public void performAggression();
}
then in dog:
public class Dog implements Animal {
private String name;
public Dog(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
#Override
public void makeNoise() {
System.out.println("Woof");
}
#Override
public void performAggression(){
biteLeash();
}
private void biteLeash() {
System.out.println("Leash snapped!");
}
}
lastly, the cat:
public class Cat implements Animal {
private String name;
public cat(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
#Override
public void makeNoise() {
System.out.println("Meow");
}
#Override
public void performAggression(){
hiss();
}
private void hiss() {
System.out.println("Hisssssss");
}
}
This way you can in you main class just do as following:
public class test{
public test(){
dog = new Dog("King");
cat = new Cat("MissPrincess");
}
public void performAggression(Animal animal){
animal.performAggression();
}
The bonus you get is, you can pass whatever class you want to a method, as long as they implements the same interface, as shown in the test class above in the method performAggression(Animal animal)
All the test class needs to know is those 3 methods, everything else can be done internally in the respective classes without test class needs to know anything about it, hence the "private" visibility on the biteLeash() and hiss() methods.
You end up with a very low coupling and easy to edit later on.
By doing this you effectively also achieve high cohesion because you don't have to get involved in mile long if/ifelse/ifelse...(so on) to determine what kind of class you are dealing with.
Operator instanceof tends to scale well only when applied to interfaces. The reason is that an interface partitions your domain in two: some objects are instances of classes which implement the interface, and the others are not. There is very likely no way that introducing a new class will break your current algorithms that rely on if (x instanceof ISomething) because the new class will either implement ISomething or not. If it does, the if body should cast x to ISomething and make good use of it; if it doesn't then the body of the if is probably of no interest to x.
This is different from the approach in which instanceof is applied to classes. For instance, seals do bark but they are not dogs: you cannot inherit Seal from Dog or viceversa. Hence, as you hinted, you are aware of the fact that if you use instanceof to check whether you can make x bark, you may end up with abominations like this:
if (x instanceof Dog) {
((Dog)x).bark();
}
else if (x instanceof Seal) {
((Seal)x).bark();
}
The solution is to have an interface ICanBark and test for it:
if (x instanceof ICanBark) {
((ICanBark)x).bark();
}
This scales well if you add more animals, whether they can bark or not. But it doesn't scale well if you want to add more noises, because you may be tempted to introduce more interfaces like ICanMeow and the like.
The solution is avoid to be in that situation; ICanBark and ICanMeow are obviously the same behavior IMakeNoise so that there is a single interface implemented by Dog, Cat and Seal.
I'm not a fan of the animal/dog/cat/noise example in the context of polymorphism. Instead I'll show you a real world example of a component system I was working on some time ago. In a component system, components are installed on entities to give them additional behavior. For instance, a monster in a videogame is an entity with some component installed (this stuff is inspired from the Unity 5 engine):
IAudioSource
IRenderer
IMovementAI
ILiving
The four classes that may implement that behaviours may well be something along the lines of:
ScaryGruntingSound
MeshOpenGLRender
StupidQuadrupedAI
Armorless
If you have a collection of entities then it is then totally acceptable (and it is going to scale well) if you instanceof for the interfaces:
for (Entity e : entities) {
for (Component c : e.getComponents()) {
if (c instanceof IAudioSource) {
((IAudioSource)c).play();
}
...
if (c instanceof IUserInput) {
((IUserInput)c).poll();
}
}
}
Since monsters are not controlled by the player, c instanceof IUserInput fails and everybody is happy. The reason why this use of instanceof rocks and the ICanBark/ICanMeow sucks is because IAudioSource/IRenderer/IMovementAI/ILiving are four totally unrelated aspects of what it means to be a monster, while ICanBark/ICanMeow are two manifestations of the same aspect (and should be instead handled by merging them into IMakeNoise).
Edit
I did consider having biteleash() in Animal which does nothing, and overriding it in Dog
It is a clunky solution and I believe it could only be motivated by performance reasons. If I'm not mistaken, Swing for Java uses such a pattern occasionally.
Is there a point to using interface types in implementations, or should you only use them as part of the public interface of a class or interface?
Example (Java):
public class SomeClass {
// Declare list as..
private List<Object> list = new ArrayList<Object>();
// or...
private ArrayList<Object> list = new ArrayList<Object>();
// Does it matter which way list is declared if it's part
// of the private implementation?
// This parameter should be the most general interface type
// allowed because it's public-facing.
public void someMethod(List<Object> list) {
// ...
}
}
By defining them as abstract as possible, you're hiding implementation details. Should you ever wish to use a different subclass from List<T> instead of ArrayList<T>, then you can do so without breaking code everywhere.
Always make it as abstract as possible while still having the methods available that you need. That way your implementation is as flexible as possible.
For example, I am a person with a pet. Right now I have a cat, but what if I get on a vacation to Africa and happen to see a very awesome elephant? My cat will starve because nobody gave her food and I will put the elephant in my pocket back to Belgium. If I were to define it as a cat, I would have to change my entire class. Instead, I define it as an animal.
public class Person {
String name;
Animal pet;
// Getters & Setters + Constructor
}
public abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Cat extends Animal {
public Cat() { super("Cat")); }
}
public class Elephant extends Animal {
public Elephant() { super("Elephant")); }
}
public class Lion extends Animal {
public Lion() { super("Lion")); }
}
So when I make a new Person:
Person bestPersonInTheWorld = new Person();
bestPersonInTheWorld.setName("Jeroen");
bestPersonInTheWorld.setPet(new Cat());
I can simply kill the cat
bestPersonInTheWorld.dontFeedForTwoWeeks();
And I put my Elephant in the yard:
bestPersonInTheWorld.setPet(new Elephant());
Nothing has to be changed when it comes to implementation.
The only examples of polymorphic method overriding I ever see involve methods that take no parameters, or at least have identical parameter lists. Consider the common Animal/Dog/Cat example:
public abstract class Animal
{
public abstract void makeSound();
}
public class Dog extends Animal
{
public void makeSound()
{
System.out.println("woof");
}
}
public class Cat extends Animal
{
public void makeSound()
{
System.out.println("meow");
}
}
public class ListenToAnimals
{
public static void main(String[] args)
{
AnimalFactory factory = new AnimalFactory();
Animal a = factory.getRandomAnimal(); // generate a dog or cat at random
a.makeSound();
}
}
In this case, everything works out just fine. Now let's add another method that gets partially implemented in the abstract class while getting the more specific behavior in the subclasses:
public abstract class Animal
{
public abstract void makeSound();
public void speak(String name)
{
System.out.println("My name is " + name);
}
}
public class Dog extends Animal
{
public void makeSound()
{
System.out.println("woof");
}
public void speak(String name)
{
super.speak(name);
System.out.println("I'm a dog");
}
}
public class Cat extends Animal
{
public void makeSound()
{
System.out.println("meow");
}
public void speak(String name, int lives)
{
super.speak(name);
System.out.println("I'm a cat and I have " + lives + " lives");
}
}
public class ListenToAnimals
{
public static void main(String[] args)
{
AnimalFactory factory = new AnimalFactory();
Animal a = factory.getRandomAnimal(); // generate a dog or cat at random
a.makeSound();
// a.speak(NOW WHAT?
}
}
In that last (commented) line of the main method, I don't know what to put there because I don't know what type of Animal I have. I didn't have to worry about this before because makeSound() didn't take any arguments. But speak() does, and the arguments depend on the type of Animal.
I've read that some languages, such as Objective-C, allow for variable argument lists, so an issue like this should never arise. Is anyone aware of a good way to implement this kind of thing in Java?
You are confusing method overriding and method overloading. In your example the Cat class has two methods:
public void speak(String name) // It gets this from its super class
public void speak(String name, int lives)
Overloading is a way to define methods with similar functions but different parameters. There would be no difference if you had named the method thusly:
public void speakWithLives(String name, int lives)
To avoid confusion the recommendation in java is to use the #Override annotation when you are attempting to override a method. Therefore:
// Compiles
#Override
public void speak(String name)
// Doesn't compile - no overriding occurs!
#Override
public void speak(String name, int lives)
EDIT: Other answers mention this but I am repeating it for emphasis. Adding the new method made the Cat class no longer able to be represented as an Animal in all cases, thus removing the advantage of polymorphism. To make use of the new method you would need to downcast it to the Cat type:
Animal mightBeACat = ...
if(mightBeACat instanceof Cat) {
Cat definitelyACat = (Cat) mightBeACat;
definitelyACat.speak("Whiskers", 9);
} else {
// Definitely not a cat!
mightBeACat.speak("Fred");
}
The code inspection tool in my IDE puts a warning on the instanceof as the keyword indicates possible polymorphic abstraction failure.
Your example Cat isn't polymorphic anymore, since you have to know it's a Cat to pass that parameter. Even if Java allowed it, how would you use it?
As far as I know java doesn't allow you to do that. speak(name, lives) is now just the Cat's function. Some languages do allow this type of flexibility. To force java to allow this, you can make the paramater an array of objects or some other collection.
However, consider that when you call speak, you now must know which parameters to pass in regardless, so the point is somewhat moot.
When you call a polymorphic method as:
a.speak("Gerorge");
You don't need to know what type of Animal has instantiated because this is the objective of polymorphism. Also since you have user the sentence:
super.speak(name);
Both Cat an Dog will have the behavior of Animal plus the own behavior.
You can do
public void speak(Map ... mappedData)
{
System.out.println("My name is " + mappedData.get("name")+ " and I have "+mappedData.get("lives");
}
However, I would advise making lives an instance variable of Cat and have your factory pass a default value (or have the constructor have a default parameter for it).
In this case best way is to use a DTO,
public class SpeakDTO
{
//use getters and setters when you actually implement this
String name;
int lives;
}
public class Dog extends Animal
{
public void speak(SpeakDTO dto)
{
super.speak(dto.name);
System.out.println("I'm a dog");
}
}
public class Cat extends Animal
{
public void speak(SpeakDTO dto)
{
super.speak(dto.name);
System.out.println("I'm a cat and I have " + dto.lives + " lives");
}
}
public class ListenToAnimals
{
public static void main(String[] args)
{
AnimalFactory factory = new AnimalFactory();
Animal a = factory.getRandomAnimal(); // generate a dog or cat at random
a.makeSound();
SpeakDTO dto = new SpeakDTO();
dto.name = "big cat";
dto.lives = 7;
a.speak(dto);
}
}
If you want to make a call like that, you could use reflection to get the class:
if (a.getclass() == Cat.class) {
// speak like a cat
} else if (a.getclass() == Dog.class) {
.
.
.
Of course this might not be the best design, and reflection should be used with care.
Java also has variable argument lists, but I'd argue that's not the "best" way to do it, at least not in all circumstances.
When subclasses have behavior that isn't defined by the interface, you don't have many options in Java that aren't verbose or a bit wonky.
You could have a speak () that takes a marker interface and delegate arg construction to a factory. You could pass a parameter map. You could use varargs.
Ultimately, you need to know what to pass to the method, no matter what language.
I agree with the comments about how you've really broken polymorphism if you must know the type of object before you can call the speak method. If you absolutely MUST have access to both speak methods, here is one way you could implement it.
public class Animal {
public void speak(String name) {
throw new UnsupportedOperationException("Speak without lives not implemented");
}
public void speak(String name, int lives) {
throw new UnsupportedOperationException("Speak with lives not implemented");
}
}
public class Dog extends Animal {
public void speak(String name) {
System.out.println("My name is " + name);
System.out.println("I'm a dog");
}
}
public class Cat extends Animal {
public void speak(String name, int lives) {
System.out.println("My name is " + name);
System.out.println("I'm a cat and I have " + lives + " lives");
}
}
Alternately you can put the UnsupportedOperationExceptions into the child classes (or you might want to used a checked exception). I'm not actually advocating either of these, but I think this is the closest way to implement what you requested, and I have actually seen systems that used something like this.