Obviously, this results in a compilation error because Chair is not related to Cat:
class Chair {}
class Cat {}
class Test {
public static void main(Strin
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
.