If I am understanding correctly:
"A factory constructor affords an abstract class to be
instantiated by another class, despite being abstract."
As example:
abstract class Animal {
String makeNoise(String sound);
String chooseColor(String color);
factory Animal() => new Cat();
}
class Cat implements Animal {
String makeNoise(String noise) => noise;
String chooseColor(color) => color;
}
The above allows me to do this:
Cat cat = new Animal();
var catSound = cat.makeNoise('Meow');
var catColor = cat.chooseColor('black');
print(catSound); // Meow
And it also prevents me from doing this:
class Dog implements Animal {
int age;
String makeNoise(String noise) => noise;
String chooseColor(color) => color;
}
Dog dog = new Animal(); // <-- Not allowed because of the factory constructor
So if I am correct with all this, I am led to ask why the extra code for Animal?
If you intend on using a factory constructor for animal, which creates only cats, why not just have a Cat class with the required methods/properties?
Or, is the purpose of the Animal class with a factory constructor like above, really an interface specifically designed for Cat class only?