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
}
}
Yes, you can. If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.
A type cast—or simply a cast— is an explicit indication to convert a value from one data type to another compatible data type. A Java interface contains publicly defined constants and the headers of public methods that a class can define.
Press Ctrl+Shift+R and then choose Convert Abstract Class to Interface.
Do not add the method to the interface. If the method is relevant only for that one implementation, only add it to that one. The point of the interface is to abstract the common elements of every factory, so a method specific to a single factory should not be in the general factory interface.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With