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 }
  • 相关阅读:
    mac OS 截图方法
    MAC OS上JAVA1.6 升级1.7,以及 maven3.2.1配置
    maven 安装设置方法
    STemWin移植
    uIP使用记录
    define宏定义细节及uCOS中宏定义技巧
    实验室播放视频步骤
    光通信零碎知识
    论文笔记6
    OFDMA
  • 原文地址:https://www.cnblogs.com/zeon/p/13500915.html
Copyright © 2011-2022 走看看