JAVA中的向上转型与向下转型

一、向上转型。

通俗地讲即是将子类对象转为父类对象。此处父类对象可以是接口。

1,向上转型中的方法调用。

看下面代码:

package com.wensefu.others;
public class Animal {
	
	public void eat(){
		System.out.println("animal eatting...");
	}
}
class Bird extends Animal{
	
	public void eat(){
		System.out.println("bird eatting...");
	}
	
	public void fly(){
		
		System.out.println("bird flying...");
	}
}
package com.wensefu.others;
public class Human {
	public void sleep() {
		System.out.println("Human sleep..");
	}
}
class Male extends Human {
	@Override
	public void sleep() {
		System.out.println("Male sleep..");
	}
}
class Female extends Human {
	@Override
	public void sleep() {
		System.out.println("Female sleep..");
	}
}
class Main{
	
	public static void main(String[] args) {
		
		Animal b=new Bird(); //向上转型
		b.eat(); 
		//! error: b.fly(); b虽指向子类对象,但此时丢失fly()方法
		dosleep(new Male());
		dosleep(new Female());
	}
	
	public static void dosleep(Human h) {
		h.sleep();
	}
}

注意这里的向上转型:
        Animal b=new Bird(); //向上转型
        b.eat();

此处将调用子类的eat()方法。原因:b实际指向的是Bird子类,故调用时会调用子类本身的方法。

需要注意的是向上转型时b会遗失除与父类对象共有的其他方法。如本例中的fly方法不再为b所有。

2,向上转型的好处。

看上面的代码,

    public static void dosleep(Human h) {
        h.sleep();
    }

这里以父类为参数,调有时用子类作为参数,就是利用了向上转型。这样使代码变得简洁。不然的话,
如果dosleep以子类对象为参数,则有多少个子类就需要写多少个函数。这也体现了JAVA的抽象编程思想。

二、向下转型。

与向上转型相反,即是把父类对象转为子类对象。

看下面代码:

package com.wensefu.other1;
public class Girl {
	public void smile(){
		System.out.println("girl smile()...");
	}
}
class MMGirl extends Girl{
	
	@Override
	public void smile() {
		
		System.out.println("MMirl smile sounds sweet...");
	}
	public void c(){
		System.out.println("MMirl c()...");
	}
}
class Main{
	
	public static void main(String[] args) {
		
		Girl g1=new MMGirl(); //向上转型
		g1.smile();
		
		MMGirl mmg=(MMGirl)g1; //向下转型,编译和运行皆不会出错
		mmg.smile();
		mmg.c();
		
		
		Girl g2=new Girl();
//		MMGirl mmg1=(MMGirl)g2; //不安全的向下转型,编译无错但会运行会出错
//		mmg1.smile();
//		mmg1.c();
/*output:
* CGirl smile sounds sweet...
* CGirl smile sounds sweet...
* CGirl c()...
* Exception in thread "main" java.lang.ClassCastException: com.wensefu.other1.Girl
* at com.wensefu.other1.Main.main(Girl.java:36)
*/
		if(g2 instanceof MMGirl){
			MMGirl mmg1=(MMGirl)g2; 
			mmg1.smile();
			mmg1.c();
		}
		
	}
}

Girl g1=new MMGirl(); //向上转型
        g1.smile();
       MMGirl mmg=(MMGirl)g1; //向下转型,编译和运行皆不会出错

这里的向下转型是安全的。因为g1指向的是子类对象。


Girl g2=new Girl();
MMGirl mmg1=(MMGirl)g2; //不安全的向下转型,编译无错但会运行会出错

运行出错:

Exception in thread "main" java.lang.ClassCastException: com.wensefu.other1.Girl
    at com.wensefu.other1.Main.main(Girl.java:36)
如代码所示,可以通过instanceof来防止出现异常。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值