下塑造型
关于下塑造型,以前一直没有弄明白,因为老是出抛出“Exception in thread "main" java.lang.ClassCastException:”。然后看书发现,原来用下逆告型之前需要用instanceof进行检测父类对像类型是否为子类类型。如果是,才可以进行强制转换。如:
//super Class public class Person { public void print() { out.println("this is the person"); }
}
public class Student extends Person {
public void print() {
out.println("this is the student");
}
public void printHello() {
out.println("say hello from student.");
}
}
然后在main 方法里面这样用: public static void main(String args) { Student s = new Student();//上朔造型 Student sss=(Student)(new Person()); sss.print(); }
这样肯定会报错,那么我们要如下进行编程:
public static void main(String args) {
Person p = new Student();//上朔造型
if(p instance of Student){
Student sss=(Student)(new Person());//下塑造型
sss.print();
}
只能上塑造型这样才会打印出“this is the student”想一想,用到下塑造型,必须先上塑造型才能下塑造型,那样又有什么意义呢?显然下塑造型不是用在这种地方。那么用在哪里呢?在一声明了一个父类类型数组,且里面存放着父类的不同子类对像的时候,就需要用到下塑造型了。如下例子:
//super Class public class Person { public void print() { out.println("this is the person"); }
}
public class Student extends Person {
public void print() { out.println("this is the student"); }
public void printHello() {
out.println("say hello from student."); } }
public class Farmer extends Person {
public void print() {
System.out.println("the is the farmer."); }
public void printHello() {
out.println("say hello from farmer."); } }
public class Test { public static void main(String args) { Student s = new Student(); Farmer f = new Farmer(); Teacher t = new Teacher();
Person persons = new Person;
persons = s; persons = f; persons = t;
Student sss = (Student) (new Person());
for (int i = 0; i < 3; i++) {
Person p = persons*; if (p instanceof Student) { Student s1 = (Student) p; s1.print(); s1.printHello(); } else if (p instanceof Teacher) { Teacher s1 = (Teacher) p; s1.print(); s1.printHello(); } else if (p instanceof Farmer) { Farmer s1 = (Farmer) p; s1.print(); s1.printHello(); }
}
} }
这样就可以一一分流出父类数组中的一个个子类对像,并且调用只属天它们自己的方法"printHello()",从而达到了下塑造型的目的