第7周動手動腦
阿新 • • 發佈:2018-11-01
1.“型別轉換”知識點考核
package kethird; class Mammal{} class Dog extends Mammal {} class Cat extends Mammal{} public class TestCast { public static void main(String args[]) { Mammal m; Dog d=new Dog(); Cat c=new Cat(); m=d; //d=m; d=(Dog)m; //d=c;//c=(Cat)m; } }
d=m和d=c導致編譯錯誤,c=(Cat)m導致執行錯誤。
子類物件可以直接賦給基類變數。 基類物件要賦給子類物件變數,必須執行型別轉換,
其語法是: 子類物件變數=(子類名)基類物件名;
如果型別轉換失敗Java會丟擲以下這種異常: ClassCastException
2.子類父類擁有同名的方法時
package kethird; public class ParentChildTest { public static void main(String[] args) { Parent parent=newParent(); parent.printValue(); Child child=new Child(); child.printValue(); parent=child; parent.printValue(); parent.myValue++; parent.printValue(); ((Child)parent).myValue++; parent.printValue(); } }class Parent{ public int myValue=100; public void printValue() { System.out.println("Parent.printValue(),myValue="+myValue); } } class Child extends Parent{ public int myValue=200; public void printValue() { System.out.println("Child.printValue(),myValue="+myValue); } }
當子類與父類擁有一樣的方法,並且讓一個父類變數引用一個子類物件時,到底呼叫哪個方法,由物件自己的“真實”型別所決定,這就是說:物件是子型別的,它就呼叫子型別的方法,是父型別的,它就呼叫父型別的方法。