【转帖】Java对象的强制类型转换

在java中强制类型转换分为基本数据类型和引用数据类型两种,这里讨论引用数据类型。

在Java中由于继承和向上转型,子类可以非常自然地转换成父类,但是父类转换成子类则需要强制转换。因为子类拥有比父类更多的属性、更强的功能,所以父类转换为子类需要强制。

构建 Son 和 Father 两个类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

class Father{

     

    public void eat(){

        System.out.println("father is eating!");

    }

     

    public void sleep(){

        System.out.println("father is sleeping!");

    }

     

}

 

class Son extends Father{

     

    public void sleep(){

        System.out.println("son is sleeping!");

    }

     

    public void play(){

        System.out.println("son is playing!");

    }

}

  

首先构造一个Son对象,然后用一个Father类型变量引用它:

1

Father father = new Son();

在这里Son 对象实例被向上转型为father了,但是请注意这个Son对象实例在内存中的本质还是Son类型的,只不过它的能力临时被消弱了而已,现在我们将其对象类型还原!

1

Son son = (Son) father;  

其实father引用仍然是Father类型的,只不过是将它的能力加强了,将其加强后转交给son引用了,Son对象实例在son的变量的引用下,恢复真身,可以使用全部功能了。

看一下整体效果:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

public class Test {

 

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        Father father = new Son();

        father.sleep();

        father.eat();

        System.out.println(" ");

        Father f = new Son();

        Son son = (Son) f;

        son.eat();

        son.sleep();

        son.play();

    }

 

}

程序输出:

1

2

3

4

5

6

son is sleeping!

father is eating!

  

father is eating!

son is sleeping!

son is playing!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值