zoukankan      html  css  js  c++  java
  • Java

    以下Animal为父类,Dog,Cat作为子类,分别继承Animal

    class Animal{
        public void shout(){
            System.out.println("叫了一声");
        }
    }
    
    class Dog extends Animal{
        public void shout() {
            System.out.println("旺旺旺");
        }
        public void seeDoor() {
            System.out.println("看门中");
        }
    }
    
    class Cat extends Animal{
        public void shout() {
            System.out.println("喵喵喵");
        }
    }

    总结:

      1. Dog对象转成Animal对象可行,如d2

          Cat对象转成Animal对象可行,如c2

      2. d2作为Animal对象转成Dog对象可行。如d3,且可执行一个Dog特有的方法

      3. c2作为Animal对象转成Dog对象,编译通过,运行报错,显示 java.lang.ClassCastException,类型转化出错

    实例代码:

    1. Dog对象转成Animal对象可行,如d2

        Cat对象转成Animal对象可行,如c2

    public class TestPoym{
        public static void main(String[] args) {
            Dog d1 = new Dog();
            animalCry(d1);
            Animal d2 = new Dog();  //向上转型
            animalCry(d2);

          Animal c1 = new Cat();
          animalCry(c1);
          Animal c2 = new Cat();
          animalCry(c2);

        }
        
        static void animalCry(Animal a) {
            a.shout();
        }
    }

    结果:

    2. d2作为Animal对象转成Dog对象可行。如d3,且可实现一个Dog特有的方法,看门

    public class TestPoym{
        public static void main(String[] args) {
            Dog d1 = new Dog();
            animalCry(d1);
            Animal d2 = new Dog();  //向上转型
            animalCry(d2);
            Animal c1 = new Cat();
            animalCry(c1);
            Animal c2 = new Cat();
            animalCry(c2);
            
            Dog d3 = (Dog)d2;  //向下转型
            d3.seeDoor();
            
        }
        
        static void animalCry(Animal a) {
            a.shout();
        }
    }

    结果:

    3.  c2作为Animal对象转成Dog对象,编译通过,运行报错,显示 java.lang.ClassCastException,类型转化出错

    代码:

    public class TestPoym{
        public static void main(String[] args) {
            Dog d1 = new Dog();
            animalCry(d1);
            Animal d2 = new Dog();  //向上转型
            animalCry(d2);
            Animal c1 = new Cat();
            animalCry(c1);
            Animal c2 = new Cat();
            animalCry(c2);
            
            Dog d3 = (Dog)d2;  //向下转型
            d3.setDoor();
            
            Dog c3 = (Dog)c2;  //编译通过,运行出错,显示强制转换出错
        }
        
        static void animalCry(Animal a) {
            a.shout();
        }
    }

    结果:

  • 相关阅读:
    常用: JS 获取浏览器窗口大小
    教你开发jQuery插件
    JS基础篇--JS的event.srcElement与event.target(触发事件对象)
    javascript中基本类型和引用类型的区别分析
    代码风格与文件模板
    定制外观
    安装与使用
    with as 如何工作
    面向对象进阶
    mro具体解释
  • 原文地址:https://www.cnblogs.com/kl-1998/p/10641089.html
Copyright © 2011-2022 走看看