Casting a class to an unrelated interface

后端 未结 1 1819
一向
一向 2020-11-28 15:00

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         


        
相关标签:
1条回答
  • 2020-11-28 15:43

    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.

    0 讨论(0)
提交回复
热议问题