Out of mere curiosity, is it possible to assign a variable to two types?
Since I don’t have my technical terms straight in this matter, let me clarify a bit. Normally you would have a static and dynamic type:
Animal a = new Dog();
Where the dynamic type has to inherit the static type:
public class Dog extends Animal {...}
But is it possible to ensure that the dynamic type extends/implements multiple types?
So that the Dog has to extend the Animal-class and implement an interface?
I’d imagine something like:
Animal [implements Happy] a = new Dog();
I’m quite sure it’s just crazy talk, but is it possible? And if not, what’s the closest alternative?
I’m thinking this only would be relevant in cases of ensuring a variable is of an interface you made yourself and a class that you cannot edit.
One way I can think of is determining it runtime by casting it every time you use it:
try {
@SuppressWarnings("unused")
Animal a = (Happy) new Dog();
} catch (ClassCastException e) {
//Is not of type Happy
}
//Using a method from the Happy-interface
try {
((Happy)a).smile();
} catch (ClassCastException e) {
//Is not of type Happy
}
No, it is not possible directly. You can think of some workarounds like:
And then use that type. Of course your classes must extend
HappyAnimal, it won’t work if they extendAnimaland implementHappydirectly.