zoukankan      html  css  js  c++  java
  • 多态中的向上转型和向下转型

    package ren.redface.demo;
    
    /*
     *     多态中的向上转型和向下转型:
     * 
     *  引用类型之间的转换
     *      向上转型
     *          由小到大(子类型转换成父类型)
     *      向下转型
     *          由大到小
     *  基本数据类型的转换
     *      自动类型转换
     *          由小到大
     *          byte short char --- int --- long --- float --- double
     *      强制类型转换
     *          由大到小
     */
    public class MethoDemo {
        public static void main(String[] args) {
            Animal2 a = new Dog();//向上转型
            //a.eat();
            
            Dog d = (Dog)a;//向下转型
            d.swim();
            d.eat();
            
        }
    }
    
    class Animal2 {
        public void eat() {
            System.out.println("吃东西");
        }
    }
    
    
    class Dog extends Animal2 {
        public void eat() {
            System.out.println("啃骨头");
        }
        
        public void swim() {
            System.out.println("狗刨");
        }
    }

    打印结果:

    狗刨
    啃骨头
     实例二:
    package ren.redface.demo;
    

    /*

     * 多态的优缺点

     * 优点:可以提高可维护性(多态前提所保证的),提高代码的可扩展性

       缺点:无法直接访问子类特有的成员

     */

    public class MethoDemo {
        public static void main(String[] args) {
            MiFactory factory = new MiFactory();
            factory.createPhone(new MiNote());
            
            factory.createPhone(new RedMi());
        }
    }
    
    class MiFactory {
        
        public void createPhone(Phone p) {
            p.call();
        }
    }
    
    interface Phone {
        public void call();
    }
    
    //小米Note
    class MiNote implements Phone{
        public void call() {
            System.out.println("小米Note打电话");
        }
    }
    
    //红米
    class RedMi implements Phone {
        public void call() {
            System.out.println("红米打电话");
        }
    }

    打印结果:

    小米Note打电话
    红米打电话
  • 相关阅读:
    成立仅8个月的个人网站,月收入几十万美金
    Dynamics AX Bitmap to Image File
    孤儿药与长尾商品的网络营销
    How to control printer orientation(Landscape / Portrait) for an AX report in X++
    长城坑爹宽带,劫持用户DNS赚取购物返利
    2014年最大福利:185个Google排名因素!免费电子书下载
    火狐用户评价
    冲刺5
    《构建之法》阅读笔记03
    冲刺4
  • 原文地址:https://www.cnblogs.com/ooo888ooo/p/12694332.html
Copyright © 2011-2022 走看看