(6) --Polymorphism之深入理解(一)

Q 10:请谈谈你对多态,继承,封装和动态绑定(dynamic binding)的理解?
A 10:
    多态:是指对于一个给定类型的引用可以指向不同类型的对象,并在其方法调用时会自动地选择其真正指向对象的特定方法.换个角度来说,多态是一种从上底到上的方法调用形式(in a nutshell,polymorphism is a bottom-up method call).Java里的用多态的好处是,我们可以在不修改调用代码(当然这个调用代码本身使用了具有多态特性的类和接口)的情况下,很容易地添加新的实现类.多态背后的机制就是我们说的动态绑定.

    继承:是指在一个子类中引入父类的行为方式(即methods)和状态(即variables),这样我们在子类中就可以访问.继承里最为重要的一个好处是,利用继承我们可以更高效简洁地重用代码(现在我能想到最给体现继承优势的是设计模式中的template pattern).

    Java中有两种方式来实现继承:
        1,implemention ineritance(已有逻辑的继承):
            You can extend an application’s functionality by reusing functionality in the parent class by inheriting all or some of the operations already implemented. In Java, you can only inherit from one uperclass. Implementation inheritance promotes reusability but improper use of class inheritance can cause programming nightmares by breaking encapsulation and making future changes a problem. With implementation inheritance, the subclass becomes tightly coupled with the superclass. This will make the design fragile because if you want to change the superclass, you must know all the details of the subclasses to avoid breaking them. So when using implementation inheritance, MAKE SURE THAT THE SUBCLASSES DEPEND ONLY ON THE BEHAVIOR OF THE SUPERCLASS, NOT ON THE ACTUAL IMPLEMENTATION. For example in the above diagram, the subclasses should only be concerned about the behavior known as area() but not how it is implemented.

        2,interface inheritance(接口的继承):
            (aka type inheritance): This is also known as subtyping. Interfaces provide a mechanism for specifying a relationship between otherwise unrelated classes, typically by specifying a set of common methods each implementing class must contain. Interface inheritance promotes the design concept of program to interfaces not to implementations. This also reduces the coupling or implementation dependencies between systems. In Java, you can implement any number of interfaces. This is more flexible than implementation inheritance because it won’t lock you into specific implementations which make subclasses difficult to maintain. So care should be taken not to break the implementing classes by modifying the interfaces.

    那如何选择这两种方式呢?interface inheritance优先,因为这样可以做到基于接口编程从而降低代码耦合.再有,我们也可以在composition的帮助下利用interface inheritance来重用代码.

 

(to be continued)

你可能感兴趣的:(java,设计模式,编程,面试,javaee)