|
第一次发帖,竟然只有一个回复的,觉得有点有点悲哀,还是自己找答案吧。 首先,多态和动态绑定的意思: The fact that an object variable can refer to multiple actual types is called polymorphism. Automatically selecting the appropriate method at run time is called dynamic binding. 【Core Java2】 一个对象变量实际上能指向多种类型就是多态。而这个变量又能在运行时自动的选择适当的方法来调用就叫动态绑定。 也就是说多态就是能一个变量能指向多种类型的对象,而它自身就具有选择适当方法的功能,这个功能就是动态绑定。(自己的理解)。因此,二楼说的也很正确,father在定义的时候就是个Father类,实际上指向的是一个son类。因此,它实际上就既是一个son类,也是一个father类(但归根到底,它是一个Son类)。如果Son类中的方法将它覆盖了,它就只能调用子类中的方法(因为前面的方法对它是不适用的)。这也是在类设计过程中的“is a”规则,也可以说是置换法则(substitution principle)。引用Core Java2: A simple rule enables you to know whether or not inheritance is the right design for your data. The "is-a" rule states that every object of the subclass is an object of the superclass. Another way of formulating the "is-a" rule is the substitution principle. That principle states that you can use a subclass object whenever the program expects a superclass object. 动态绑定中的“根据方法签名正确选择适当的方法”,选择实际上也是指在父类和子类中去选择正确的方法。我之所以搞混了,主要原因是因为在书中的那一节的标题是动态绑定(Dynamic Binding),但接下来介绍的却是调用对象方法的执行过程。仅在其中的第3点中介绍的是动态绑定。因此这里要补充一下,动态绑定是否是根据方法签名来调用的,还有待商榷(看各人自己的理解)。下面引用第三点: 3.If the method is private, static, final, or a constructor, then the compiler knows exactly which method to call. (The final modifier is explained in the next section.) This is called static binding. Otherwise, the method to be called depends on the actual type of the implicit parameter, and dynamic binding must be used at run time. In our example, the compiler would generate an instruction to call f(String) with dynamic binding.【Core Java2】 这里也就是说,对动态绑定起决定作用的,其实是隐式参数(implicit parameter)。下面我自己对隐式参数作一下解释,隐式参数是在方法调用中没有在参数列表中写出来的参数。如,在调用方法e.getSalary(arg1,arg2)时,实际上在定义中应该是this.getSalary(arg1,arg2),this=e 这个this参数,也就是e的实际类型就是隐式参数。(按前面的说的,似乎隐式参数并不在方法签名的范围内)。而要看e的实际引用类型来判断选择哪一个方法就是动态绑定了。 小结:回头看来,确实是我对多态一知半解,理解不深。当然,也可能是以前错误理解的“多态是由方法的重载来实现的”这一思想误导了自己。另外看书不够仔细也是一个原因(如前面提到的,对动态绑定的理解,误以为前面有个动态绑定的标题,后面讲的全都是动态绑定实现的过程。)当然,上面虽然引用了很多Java核心技术中的原话,但主要也只是自己的理解,可能还有理解不全面,甚至错误的地方,希望后面仍然有人讨论。
|