explicit casting from super class to subclass

2019-01-01 07:05发布

public class Animal {
    public void eat() {}
}

public class Dog extends Animal {
    public void eat() {}

    public void main(String[] args) {
        Animal animal = new Animal();
        Dog dog = (Dog) animal;
    }
}

The assignment Dog dog = (Dog) animal; does not generate a compilation error, but at runtime it generates a ClassCastException. Why can't the compiler detect this error?

7条回答
倾城一夜雪
2楼-- · 2019-01-01 07:27

As explained, it is not possible. If you want to use a method of the subclass, evaluate the possibility to add the method to the superclass (may be empty) and call from the subclasses getting the behaviour you want (subclass) thanks to polymorphism. So when you call d.method() the call will succeed withoug casting, but in case the object will be not a dog, there will not be a problem

查看更多
登录 后发表回答