Java向上转型小议

        为了测试Java的向上转型特性,我写了四个类:Animal,Dog,Cat及测试类Test,以下就是代码及特性分析:
Animal:
package com.caolei.up;
public class Animal
{
 String color;
 String sex;
 public void move()
 {
  System.out.println("animal is moving!");
 }
 public void setColor(String color)
 {
  this.color=color;
 }
 public void setSex(String sex)
 {
  this.sex=sex;
 }
}
Cat:
package com.caolei.up;
public class Cat extends Animal
{
 String color;
 String sex;
 public void move()
 {
  color=super.color;
  sex=super.sex;
  System.out.println("the "+color+" "+sex+" cat is jumping!");
 }
 public void smile()
 {
  System.out.println("the cat is smiling!");
 }
}
Dog:
package com.caolei.up;
public class Dog extends Animal{
 String color;
 String sex;
 
 public void move()
 {
  color=super.color;
  sex=super.sex;
  System.out.println("the "+color+" "+sex+" dog is running!");
 }
 public void bark()
 {
  System.out.println("the dog is barking!");
 }
}
Test类:
package com.caolei.up;
public class Test {
 public static void main(String[] args)
 {
   //向上转型测试
  Animal a1;
   //dog类对象向上转型为Animal类对象
  a1=new Dog();
  a1.setColor("yellow");
  a1.setSex("female");
  a1.move();
  /******************************
  *a1.bark();
  *上转型后此句无法执行,
  *因为上转型对象不是父类创建的对象,
  *而是子类对象的“简化”状态,
  *它不关心子类新增的功能,
  *只关心子类继承和重写的功能。
  *******************************/

   //cat类对象向上转型为Animal类对象
  a1=new Cat();
  a1.setColor("black");
  a1.setSex("male");
  a1.move();
   /******************************
  *a1.smile()
  *同样也无法执行
  *可以发现由猫类和狗类上转型
  *得来的对象实例在调用相同方法时,
  *长生的结果并不同,这也是多态的一中体现。
  *******************************/
   }
}
测试结果:
the yellow female dog is running!
the black male cat is jumping!
结语:
        当一个类有很多子类时,并且这些子类都重写了父类中的某个方法。当使用上转型对象在调用这个方法时就可能具有多种形态(即多态)。因为不同的子类在重写父类的方法时可能产生不同的行为。也就是说,不同对象的上转型对象调用同一方法可能产生不同的行为。这样的好处是显而易见的:1.降低了程序的耦合性及增强了可扩性。2.无法窥视子类特有的域和方法,也可以算是封装吧。3.代码的复用率提高了,否则子类需要覆盖更多的父类方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值