Java的多态

2018-04-27  本文已影响0人  0x70e8

面向对象的三种特性封装,继承和多态。
封装是为了保护数据和代码重用,继承在一定程度上也是为了代码重用,另外一方面继承是为了支持多态。
那么多态到底是什么意思呢?看一下wiki百科定义:

In programming languages and type theory, polymorphism is the provision of a single interface to entities of different types. A polymorphic type is one whose operations can also be applied to values of some other type, or types. There are several fundamentally different kinds of polymorphism:

  • Ad hoc polymorphism: when a function has different implementations depending on a limited range of individually specified types and combinations. Ad hoc polymorphism is supported in many languages using function overloading.
  • Parametric polymorphism: when code is written without mention of any specific type and thus can be used transparently with any number of new types. In the object-oriented programming community, this is often known as generics or generic programming. In the functional programming community, this is often shortened to polymorphism.
  • Subtyping (also called subtype polymorphism or inclusion polymorphism): when a name denotes instances of many different classes related by some common superclass.

大致意思就是多态是对不同类型的实体提供一个单一的接口,实际上也就是抽象,这个抽象对应多个实体,且这个抽象具有多态性(在不同情况下表现不同的形态,即转化成不同的实体,但是抽象意义上他还是一个抽象而不是一个实体)所以能够处理派生于此抽象的各种实体类型。
本质不同的三种多态:

通俗来说多态就是对象在不同的场景下能表现多种形态(状态)的能力,比如对同一个消息做出不同的响应。类似于switch的处理。

class TheSuper {
 
    void overrideMethod() {
    }
    void overrideMethod(int a){}

    public static void main(String[] args) {
        TheSuper instance = new TheSuper();
        instance.overrideMethod();
        instance.overrideMethod(1);
    }
    }

}

使用不同type的参数来执行instance.overrideMethod();,就相当于在一个method中,判断参数类型(个数)然后编写对应的逻辑,如果没有多态特性的支撑,就得写类似switch的代码。我们不用这样做是因为这些判断Java的多态特性的实现帮我们做了。
在这个例子中,不同的消息就是不同的参数,不同的响应就是调用了不同的方法。
很显然,这个多态的实现并不需要继承的特性来支持。

class TheSub extends TheSuper {

    @Override
    void overrideMethod() {
        System.out.println("Thesub");
    }
     
}
class TheSub2 extends TheSuper{
    @Override
    void overrideMethod(){
        System.out.println("Thesub 2 ");
    }
}

这里子类重写了父类中的两个重载方法,在TheSub中调用:

        TheSuper s = new TheSub();
        s.overrideMethod();
        s= new TheSub2();
        s.overrideMethod();

结果是:

The sub
Thesub 2 

在这个例子中,父对象s对应不同的实体类型,表现出不同的动作。这也是多态。

上一篇 下一篇

猜你喜欢

热点阅读