I am having a problem with Factory pattern when it use with Inheritance,
This is my code
public class Animal {
public int numberOfLegs() { return 2 ;}
}
public class Cat extends Animal {
public String getSound() {return "Maaaw";}
}
public class Dog extends Animal {
public String getSound() {return "woof";}
}
public class AnimalFactory {
public Animal getAnimal(String name){
Animal an= null ;
if(name=="cat"){an = new Cat();}
else if(name=="dog"){an=new Dog();}
return an ;
}
}
public class FactoryDemo {
public static void main(String[] args) {
AnimalFactory anmF=new AnimalFactory();
Animal anm=anmF.getAnimal("cat") ;
System.out.println("legs : "+anm.numberOfLegs()); // working fine
System.out.println("sound : "+anm.getSound()); // giving error
}
}
When I run this, I can’t go to the getSound() method. It giving a error.
This’ll work fine if I define the Animal class as Abstract class,
But I want to how to deal Factory pattern such a situation like this.
The code you included, is nothing like a Factory anything. If you refer to the Factory Method Pattern then, what you implemented as part of your OP is an incorrect implementation. There are two “Factory” code designs, one is the Factory Method Pattern I indicated before (your code is definitely not that) and the Factory recommended in the Effective Java book, which is the design of choice for the Java JDK i.e. the
valueOforcreate*methods.