再提多态
记得进入Sun的面试的时候Leon就问了我Java如何实现多态。当时的答案是通过重载和继承,后者也就是动态绑定。今天看到PHP与MySQL5程序设计里面的关于PHP不支持方法重载的时候,再次引起我对“多态”这个概念的探究。首先,多态是面向对象方面的一个重要特性,它本不应该依赖于特定的编程语言。WIKI 中对Polymorphism的定义如下:
In simple terms, polymorphism is the ability of one type, A, to appear as and be used like another type, B. In strongly typed languages, this usually means that type A somehow derives from type B, or type A implements an interface that represents type B.
Operator Overloading the numerical operators +, -, /, * allow polymorphic treatment of the various numerical types integer, unsigned integer, float, decimal, etc; each of which have different ranges, bit patterns, and representations. Another common example is the use of the “+” operator which allows similar or polymorphic treatment of numbers (addition), strings (concatenation), and lists (attachment). This is a lesser used feature of polymorphism.
The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run time (this is called late binding or dynamic binding).
从中我们可以看到,其实重载(override)并不是polymorphism,只是利于国人理解的一种解释。网上好多类似的讨论,一时也把我搞糊涂了,我特意去查了一下Thinking in Java,证实了以上的说法。总结一下就是继承是多态的基础,多态使得不同对象对同一条指令做出各自不同的响应。所以我当初的答案是不准确的,但是动态多态和静态多态的概念在C++教学中普遍使用,使得在在中文中多态又多了一层含义。
而PHP不支持方法重载的很大原因也在于PHP是弱类型语言,类型本身就可以自动变更,方法重载也就省了。
