So I was messing around with down-casting, trying to find what works and what doesn't. I have three classes: a base class Animal
, and two derived classes Dog
and Cat
:
private class Animal {
}
private class Dog extends Animal {
}
private class Cat extends Animal {
}
The following code isn't allowed by the compiler for an obvious reason:
Dog dog = s.new Dog();
Cat cat = (Cat) dog;
This is because I'm casting one derived class to another derived class, which isn't possible. However, if I make Animal
an interface type and Cat
an interface type, then suddenly the compiler accepts it and doesn't say any problem, even though it isn't possible.
private interface Animal {
}
private class Dog implements Animal {
}
private interface Cat extends Animal {
}
As soon as I run the same code as before, it gives me an error, as expected.