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打电话
    红米打电话
  • 相关阅读:
    Validation failed for one or more entities
    sql 存储过程
    SQL Server分页3种方案比拼
    case when 用法
    C#如何计算代码执行时间
    透过 Jet.OLEDB 读取 Excel里面的数据
    DataBinding?资料系结?资料绑定?
    ASP.NET的OutputCache
    我想写程序#3 之 「简单地设计自己的数据表(Table)」
    我想写程序#1 之 「先确立志向」
  • 原文地址:https://www.cnblogs.com/ooo888ooo/p/12694332.html
Copyright © 2011-2022 走看看