下塑造型

关于下塑造型,以前一直没有弄明白,因为老是出抛出“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[3];

persons[0] = s;
persons[1] = f;
persons[2] = t;

Student sss = (Student) (new Person());

for (int i = 0; i < 3; i++) {

Person p = persons[i];
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()",从而达到了下塑造型的目的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值