父類不能轉換成子類
Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to Boy at Test.main(Test.java:5) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
public class Test { public static void main(String[] args) { Person person = new Person(); Boy boy = (Boy) person; boy.eat(); } } class Person { public void eat() { System.out.println("The people were eating"); } } class Boy extends Person { public void eat() { System.out.println("The boy were eating"); } }
By using a cast you're essentially telling the compiler "trust me. I'm a professional, I know what I'm doing and I know that although you can't guarantee it, I'm telling you that this animal variable is definitely going to be a dog."
Since the animal isn't actually a dog (it's an animal, you could do Animal animal = new Dog(); and it'd be a dog) the VM throws an exception at runtime because you've violated that trust (you told the compiler everything would be ok and it's not!) The compiler is a bit smarter than just blindly accepting everything, if you try and cast objects in different inheritence hierarchies (cast a Dog to a String for example) then the compiler will throw it back at you because it knows that could never possibly work. Because you're essentially just stopping the compiler from complaining, every time you cast it's important to check that you won't cause a ClassCastException by using instanceof in an if statement (or something to that effect.)
https://stackoverflow.com/questions/4862960/explicit-casting-from-super-class-to-subclass
如果使用轉型,你其實就是在告訴編譯器:“請相信我,我是一個專家,我知道我在做什么雖然我並不能保證不出問題,我告訴你這個代表動物的變量肯定是一只狗。”
因為animal不一定就是一只dog(它是一只動物,如果這只動物是一只狗,你就可以進行這個操作Animal animal=new Dog()),虛擬機將拋一個運行時異常,因為你違反了約定的信任前提(你告訴編譯器所有的都是正常的,但實際上並不是)