Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
   }
}
like image 291
enp4yne Avatar asked Oct 02 '13 16:10

enp4yne


People also ask

Can you cast a class to an interface?

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.

What is casting how it is used in interface?

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.

How do you change a class to an interface in Java?

Press Ctrl+Shift+R and then choose Convert Abstract Class to Interface.

Can you add extra methods 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.


1 Answers

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.

like image 50
Sotirios Delimanolis Avatar answered Sep 24 '22 06:09

Sotirios Delimanolis