zoukankan      html  css  js  c++  java
  • java 多态

    向上转型:我们把对某个对象的应用视为对其基类型的应用的做法视为向上转型。

        (比如一个Apple类继承自一个Fruit,Apple apple = new Fruit()这种初始化方法就叫做向上转型)

        向上转型可以忘记对象类型

    常规写法:

     1 /**
     2  * 常规写法
     3  * 2016/5/5
     4 **/
     5 package cn.Java_7;
     6 class Fruit{
     7     public void eat(){
     8         System.out.println("eat fruit");
     9     }
    10 }
    11 class Apple extends Fruit{
    12     public void eat(){
    13         System.out.println("eat apple");
    14     }
    15 }
    16 class Orange extends Fruit{
    17     public void eat(){
    18         System.out.println("eat orange");
    19     }
    20 }
    21 class Banana extends Fruit{
    22     public void eat(){
    23         System.out.println("eat banana");
    24     }
    25 }
    26 public class AllFruit {
    27     public static void eatFruit(Apple apple){
    28         apple.eat();
    29     }
    30     public static void eatFruit(Orange orange){
    31         orange.eat();
    32     }
    33     public static void eatFruit(Banana banana){
    34         banana.eat();
    35     }
    36     
    37     public static void main(String[] args) {
    38         eatFruit(new Apple());
    39         eatFruit(new Orange());
    40         eatFruit(new Banana());
    41     }
    42 
    43 }

    程序没有什么问题,可以直接运行,每种方法都有对应的类型,但是这里只有3个子类,如果有更多的子类,那么我们就要为每一种子类都要写一种对应的方法,这样代码冗余太大了。

    然后多态就出现了:

    public class AllFruit {
        public static void eatFruit(Fruit fruit){
            fruit.eat();
        }
        public static void main(String[] args) {
            eatFruit(new Apple());
            eatFruit(new Orange());
            eatFruit(new Banana());
        }

    这样同样也可以实现上面程序的功能,而且代码量也减少了很多,一共就只有一个方法来对应所有的类,如果在增加一些Fruit的子类的话也不会专门为其写对应的方法了。

    我们在来理解多态:

    多态就是一种东西多种状态,多种形式。多态也叫动态绑定、后期绑定、运行时绑定。

    (英文解释神马是前期绑定,什么是后期绑定)

    what is Early and Late Binding?

    The short answer is that early (or static) binding refers to compile time binding and late (or dynamic) binding refers to runtime binding。

     前期绑定就是编译时绑定,后期绑定就是运行时绑定。

    向上转型的写法

    1 //向上转型的写法
    2     public static void main(String[] args){
    3         Fruit apple = new Apple();
    4         Fruit orange = new Orange();
    5         Fruit banana = new Banana();
    6         apple.eat();
    7         orange.eat();
    8         banana.eat();
    9     }

     这样代码看起来就更加简介易懂了。

    多态其实就是一种让程序员将“将改变的事物和未改变的事物分离开来”的一种技术。

  • 相关阅读:
    SQL Server CHARINDEX和PATINDEX详解
    MVC ListBoxFor raises “value cannot be null” exception
    jquery.uploadify动态传递表单元素
    C# 判断一字符串是否为合法数字(正则表达式)
    jquery 操作Listbox
    JQuery 操作 ListBox间移动和ListBox内移动
    jQuery获取Select选择的Text和 Value
    SQL 语句的执行效率
    JSON 序列化长度限制问题
    C#中利用FileSystemWatcher对单个文件内容的监视
  • 原文地址:https://www.cnblogs.com/snail-lb/p/5460558.html
Copyright © 2011-2022 走看看