Java inheritance的upcasting和downcasting

upcasting一般是安全的,因为子类继承了母类所有的方法,不会报错。

downcasting一般不被允许,非法downcasting会有run time error: ClassCastException。

Example:
/* This code generates a java.lang.ClassCastException */

public class UpCastingDownCasting {
	public static void main(String[] args) {
		Person personRefVariable;
		Person teds = new Student("Ted", 2, 2000, 4.0);
		Student StudentRefVariable;
		GradStudent GradStudentRefVariable;
				
		// Same type
		personRefVariable = teds;
		
		// Does not compile as teds may not be a Student; notice we defined teds
		// as a Person variable not a Student
		// StudentRefVariable = teds;
		
		// Downcasting
		// OK as teds is actually a Student; no run-time error
		StudentRefVariable = (Student)teds;  
		
		// Downcasting
		// run-time error (ClassCastException); ted isn't a graduate student
		GradStudentRefVariable = (GradStudent)teds; 
	}
}
运行中报错:ClassCastException

可以进行强制downcasting。

方法为:先用instanceOf()来判断downcast的类是不是属于自己要cast到的子类。
Example: SafeDownCasting.java
import java.util.*;

public class SafeDownCasting {
    public static void main(String[] args) {
	ArrayList list = new ArrayList();

	list.add(new Person("John", 1));
	list.add(new Student("Laura", 20, 2000, 4.0));
	list.add(new Faculty("DrRoberts", 30, 1970));

	for (int i = 0; i < list.size(); i++) {
	    Person obj = list.get(i);
	    System.out.print(obj.getName());
	    if (obj instanceof Student) {
		Student student = (Student) obj;
		System.out.println(", admission year is " + student.getAdmitYear());
	    } else {
		System.out.println();
	    }
	}
    }
}
正常输出不报错:
John
Laura, admission year is 2000
DrRoberts

你可能感兴趣的:(Java)