I'm sure this is incredibly common with as OOP centered as Java is. In java is there a way to make a base type variable that accepts all inherited subtypes? Like if I have;
class Mammal {...}
class Dog extends Mammal {...}
class Cat extends Mammal {...}
class ABC {
private Mammal x;
ABC() {
this.x = new Dog();
-or-
this.x = new Cat();
}
}
I need the variable to be able to accept any extended version too, but not in specific one extended kind.
There are some ways that I know, but don't want to use. I could make an attribute for each subtype, then only have the one attribute actually used. Make an array and shove it in there.
Any other ideas or a way to get a "base class" type variable?
Ok since I know using polymorphic duck typing isn't a great idea in Java, but since I don't think I can avoid it. Is the only way to use subclass methods dynamically to re assign a casted version of the varible ie, I get an error with this;
Mammal x;
x = new Dog();
System.out.println(x.getClass());
x.breath();
if (x instanceof Dog) {
x.bark();
} else if (x instanceof Cat) {
x.meow();
}
Saying symbol not found, however this works;
Mammal x;
x = new Dog();
System.out.println(x.getClass());
x.breath();
if (x instanceof Dog) {
Dog d = (Dog) x;
d.bark();
} else if (x instanceof Cat) {
Cat c = (Cat) x;
c.meow();
}
That last one the only way to do it?