zoukankan      html  css  js  c++  java
  • 对象的向上转型和向下转型---Java

    1 public abstract class Animal {
    2 
    3     public abstract void eat();
    4 }
     1 public class Cat extends Animal{
     2 
     3     @Override
     4     public void eat() {
     5         System.out.println("猫吃鱼");
     6     }
     7 
     8     public void catchMouse(){
     9         System.out.println("猫抓老鼠");
    10     }
    11 }
     1 public class Dog extends Animal{
     2     @Override
     3     public void eat() {
     4         System.out.println("狗是骨头");
     5     }
     6 
     7     public void watchHouse(){
     8         System.out.println("狗看家");
     9     }
    10 }
     1 /*
     2 * 向上转型一定是安全的,正确的,没问题的,但是也有一个弊端:
     3 *       对象一旦向上转型为父类,那么就无法调用子类原本特有的内容*/
     4 public class Demo01Main {
     5 
     6     public static void main(String[] args) {
     7 
     8         //对象的向上转型,就是: 父类引用指向子类对象
     9         Animal animal = new Cat();
    10         animal.eat();
    11 
    12         //animal.catchMouse();  //错误写法
    13 
    14         //向下转型,进行"还原"动作
    15         Cat cat = (Cat) animal;
    16         cat.catchMouse();
    17 
    18         //下面是错误的向下转型
    19         //本来new的是一只猫,非要把它当狗
    20         //java.lang.ClassCastException  类转换异常
    21         Dog dog = (Dog) animal;  //错误写法  , 编译不会报错,但是运行有异常
    22     }
    23 }
     1 /*
     2 * 如何才能知道一个父类引用的对象,本来是什么子类 3 *
     4 * 格式:
     5 *       对象 Instanceof  类名称
     6 * 这将得到一个boolean布尔值结果,也就是判断前面的对象能不能当做后面类型的实例*/
     7 public class Demo02Instanceof {
     8 
     9     public static void main(String[] args) {
    10         Animal animal = new Cat();  //本来是一只猫
    11 
    12         if(animal instanceof Cat){
    13             Cat cat = (Cat) animal;
    14             cat.catchMouse();
    15         }
    16         if (animal instanceof Dog){
    17             Dog dog = (Dog) animal;
    18             dog.watchHouse();
    19         }
    20         
    21         giveMeAnPet(new Dog());
    22     }
    23 
    24     public static void giveMeAnPet(Animal animal){
    25         if(animal instanceof Cat){
    26             Cat cat = (Cat) animal;
    27             cat.catchMouse();
    28         }
    29         if (animal instanceof Dog){
    30             Dog dog = (Dog) animal;
    31             dog.watchHouse();
    32         }
    33     }
    34 }
  • 相关阅读:
    SAP 多料号展BOM
    SAP QM 检验批可用库存回转为待检验库存
    SAP QM UD检验批回转为REL待检验状态
    在ABAP中获取应用程序服务器的IP地址
    SAP连接外部数据库后批量写入数据
    Java调用Axis2用SAP WSDL生成的Stub文件
    用最新的采购信息记录更新采购单的价格——BAPI_PO_CHANGE
    SAP QM——QA01、QA02、QA03屏幕增强
    Java递归实现一、二、三级菜单查询
    ABAP——查询
  • 原文地址:https://www.cnblogs.com/zeon/p/13500915.html
Copyright © 2011-2022 走看看