Casting a class to an unrelated interface
Obviously, this results in a compilation error because Chair is not related to Cat:
class Chair {}
class Cat {}
class Test {
public static void main(String[] args) {
Chair chair = new Char(); Cat cat = new Cat();
chair = (Chair)cat; //compile error
}
}
Why is it then that I only get an exception at run time when I cast a Cat reference to the unrelated interface Furniture, while the compiler can obviously tell that Cat does not implement Furniture?
interface Furniture {}
class Test {
public static void main(String[] args) {
Furniture f; Cat cat = new Cat();
f = (Furniture)cat; //runtime error
}
}
Solution 1:
The reason this compiles
interface Furniture {}
class Test {
public static void main(String[] args) {
Furniture f; Cat cat = new Cat();
f = (Furniture)cat; //runtime error
}
}
is that you may very well have
public class CatFurniture extends Cat implements Furniture {}
If you create a CatFurniture
instance, you can assign it to Cat cat
and that instance can be casted to Furniture
. In other words, it's possible that some Cat
subtype does implement the Furniture
interface.
In your first example
class Test {
public static void main(String[] args) {
Chair chair = new Char(); Cat cat = new Cat();
chair = (Chair)cat; //compile error
}
}
it's impossible that some Cat
subtype extends Chair
unless Cat
itself extends from Chair
.