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?
If you have the following:
Then
Dogis a subtype ofMammal.Catis also a subtype ofMammal. This type polymorphism does in fact allow you to do the following:If in fact later there’s the following:
Then you can also do:
This polymorphic subtyping relationship is one of the basic tenets of object-oriented programming.
See also
On
instanceoftype comparison operatorSuppose we have the following:
Then you can use
instanceoftype comparison operator (§15.20.2) to do something like this:There are also ways to do this without
if-else; this is just given as a simple example.Note that with appropriate design, you may be able to avoid some of these kinds of subtype differentiation logic. If
Mammalhas amakeSomeNoise()method, for example, you can simply callx.makeSomeNoise().Related questions
On reflection
If you must deal with new types not known at compile-time, then you can resort to reflection. Note that for general applications, there are almost always much better alternatives than reflection.
See also