六、转型,包括:向上转型(父类引用指向子类对象),向下转型(强制类型转换)...

父类的引用指向子类的对象,但是cat属于父类,所以Animal cat = new Cat()的cat对象,不能调用子类多出来的内容,比如这里的enjoy方法 (向上转型)

public class Helloworld1 {
 public static void main(String args[]) {
  Animal cat = new Cat();
  cat.name = "tom";
  cat.sleep();
  }
 }
 class Animal {
  String name;
  public void sleep() {
   System.out.println(name+" is sleepping");
   }
  }
  class Cat extends Animal {
   String furColor;
   public void enjoy() {
   System.out.println(name+" enjoy");
     }
   }

....................................................................................................................................
向下转型:强制类型转换。

public class Helloworld1 {
 public static void main(String args[]) {
  Cat cat = new Cat();
  cat.name = "tom";
  Cat a = (Cat)cat;          //向下转型,使得cat对象转换为Cat类,这样他才能调用子类多出来的内容
  a.catchMouse();
  }
 }
 class Animal {
  String name;
  public void sleep() {
   System.out.println(name+" is sleepping");
   }
  }
  class Cat extends Animal {
   String furColor;
     public void catchMouse() {
     System.out.println("catch");
     }
   }

转载于:https://www.cnblogs.com/jianzhi20093120/archive/2012/07/17/2596587.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值