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

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

首先,java的转型是基于继承的基础上的,转型的使用一般在多态中。关于在转型中最重要的一点那就是:父类引用指向子类对象;而子类引用不能指向父类对象

向上转型与向下转型

一个简单的例子:有2个类,Animal是父类,Pig类继承自Father。

Animal a1 = new Pig();//父类引用a指向子类对象
Pig p1 = (Pig)a //子类对象的父类引用 a 赋给子类引用 p2

Animal a2 = new Animal();
Pig p2 = (Pig)a2//子类引用p2指向父类对象a2;(严格的说这里的a2是指的父类引用而不是父类的对象)
  • 向上转型:父类引用指向子类对象,而子类引用不能指向父类对象
  • 向下转型:子类对象的父类引用 赋给子类引用
向上转型在代码中的实现
package casting;
/**
 * Animal父类
 * @author wangyu
 * 
 * @create date:2017年10月12日
 */
public class Animal {

    public void eat(){
        System.out.println("animal eatting...");
    }
}
/**
 * 子类
 */
class Birds extends Animal{
    //重写父类方法
    @Override
    public void eat() {
         System.out.println("bird eatting...");  
    }

    public void fly(){
        System.out.println("bird fly...");  
    }
}
/**
 * Human子类
 * @author wangyu
 * 
 * @create date:2017年10月12日
 */
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..");  
    }  
}
/**
 * 测试类
 * @author wangyu
 * 
 * @create date:2017年10月12日
 */
public class Main {

    public static void main(String[] args) {
        Animal b=new Birds(); //向上转型  
        b.eat();   
        //! error: b.fly(); b虽指向子类对象,但此时丢失fly()方法  
        dosleep(new Male());  
        dosleep(new Female()); 
    }

    public static void dosleep(Human h) { //这里以父类为参数,调有时用子类作为参数,就是利用了向上转型。使代码简洁
        h.sleep();  
    }  
}

运行结果:
bird eatting...
Male sleep..
Female sleep..
向下转型在代码中的实现
public static void main(String[] args) {
        Animal a = new Birds(); //向上转型  
        a.eat();

        Birds b = (Birds)a;//向下转型
        b.fly();
        b.eat();

        Animal a2 = new Animal();//不安全的向下转型,编译无错但会运行会出错
        if(a2 instanceof Birds){
            Birds b2 = (Birds)a2;
            b2.fly();
            b2.eat();
        }
        /*
         * 运行出错:
            Exception in thread "main" java.lang.ClassCastException: com.wensefu.other1.Girl
                at com.wensefu.other1.Main.main()
            如代码所示,可以通过instanceof来防止出现异常。
         */
    }

运行结果:
bird eatting...
bird fly...
bird eatting...
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值