I need to create a class that can store in a variable a value of type either Person
, Dog
or Cat
.
I'd like to declare one variable because only one object of an specific type will be used to initialize the instance of the class. Declaring a variable for each type would be a waste of resources as only one would be used.
Consider this:
Class Container {
private Object object;
...
Container(Person a){
object = a;
}
Container(Dog a){
object = a;
}
Container(Cat a){
object = a;
}
...
}
And then do:
Container contA = new Container(A);
Container contB = new Container(B);
System.out.println(contA.getObject().toString());
System.out.println(contA.getObject().toString());
And ideally get the correct output in console.
I looked into generics and other stuff but was unable to find anything like what I needed. Could you point me to what I'm looking for?
The getObject()
in Container
could handle the type with an instanceof
but the return type of getObject()
would have to be Object
and that won't work.
I'm learning Java and this is really bugging me.
Should I instead use inheritance and create a subclass to handle each type?
You can use generics (how you already guessed):
public class Container<T> {
T object;
Container(T a) {
object = a;
}
T getObject() {
return object;
}
}
or an (marker) interface (a generalization). In your following code you can go on working with Mammal instead of distinguishing between Cats and Dogs:
public interface Mammal {
}
public class Container {
Mammal object;
Container(Mammal a) {
object = a;
}
Mammal getObject() {
return object;
}
}
public class Cat implements Mammal {...
public class Dog implements Mammal {...
public class Person implements Mammal {...
Interfaces relate the classes together giving them a meaning while generics do not. (Muhammad Ali)