向上转换,向下转换,强制转换浅析

向上转换,向下转换,强制转换

先来一段代码!!!

class 类人猿{

    void crySpeak(String s){
        System.out.printf(s);
    }
}
class People extends 类人猿{
    void computer(int a,int b){
        int c=a*b;
        System.out.println(c);
    }
    void crySpeak(String s){
        System.out.printf("* * *"+s+"* * * \n");
    }
}

public class Application5_9 {
        public static void main(String args[]){
            类人猿  monkey=new People();                //子类创建monkey,实体为子类,但是父类引用monkey,此时 :::monkey的实体是子类,但是功能减弱,这是向上转型
            monkey.crySpeak("I love the game");
            People people=(People)monkey;            //向下转型:这时候monkey是父类引用,这个代码是将父类引用的准换成子类引用的,才能实现本类引用本类创建的 对象,功能加强!
            people.computer(10,10);
        }

}


1.向上转型方法(People是父类,American是子类)

         People person;

         person=new American;

        People person;

        American  anAmerican=new  American();

        person=anAmerican;

       People person=new American();     / /直接转换

2.分析

      People person=new American();       //子类创建person,实体为子类,但是父类引用person,此时 :::person的实体是子类,但是功能减弱了

如果想要将其功能恢复,那么我们来分析一下,之所以功能减弱,是因为父类引用了子类创建的对象,本来子类是强大的,但是用父类引用之后就减弱了,所以,如果恢复的子类引用子类的话,是不是就会强大的呢,答案是 是的。

      运用到强制转换:

      People   people=(People)person:   // person的实体是子类,括号里的People是将要转换的类型













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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值