學過物件導向程式設計的人,都知道繼承(inheritance)與複合(composition)這兩種觀念。前者是「is a」,後者則是「has a」的關係。近年來很多人提倡「favor composition over inheritance」,我也是支持者之一,但為何這樣,三言兩語又很難講清楚。我只能說,以前維護Java程式碼的時候,那一層又一層的繼承關係讓人腦袋發脹...
所以,我们可以看到,虽然composition也可以实现inheritance的这些功能,在满足inheritance的条件下,有一大堆的delegate的代码要写。这样就平添了很多无意义的代码。 所以我们在比较这两种情形的取舍时,可以先看看新的类是否可以完全适用于父类的所有场景,如果可以使用inheritance,否则应该考虑composition。这里举的示例是一个简单...
Unlike method invocation, inheritance violates encapsulation. Since you don't know the super class implementation which may involve some unpredictable calling between different methods of super class. And it is difficult to maintain the subclass when there is a change of the super class. Be careful ...
只是写wrapper比较无聊,仅此而已。 当且仅当Class B与Class A确实是同一种对象时才使用继承。(is-a)尽管Java平台类库里有很多违反了这一原则。例如Stack不是Vector,不应该扩展Vector;Property列表不是Hash表,所以Properties不应该扩展Hashtable。——一个太晚发现的问题。 继承违反了封装,所以尽管强大,却也容易出错。
主要区别就是在 你所需表达的概念上 。如果你需要的只是现有类的某种能力,而不是该类的接口,也就是说你只是需要现有类来做某种事情,而你创建的类与该类并没有类似的接口的话,你就应该使用 composition 。而 inheritance 的应用正好相反。也就是说你需要的是现有类的接口,也就是你希望在可以使用...
Compare inheritance and composition, the two fundamental ways to relate Java classes, then practice debugging ClassCastExceptions in Java inheritance.
在Java 库中有许多明显违反这一原则的地方。例如,stack 不是 vector,因此 Stack 不应该继承 Vector。类似地,property 列表不是 hash 表,因此 Properties 不应该继承 Hashtable。在这两种情况下,复合都是可取的。 If you use inheritance where composition is appropriate, you needlessly expose implementation details...
an object of parent class or subclass. compile time polymorphism is just method overloading in Java. A method can take different variance of arguments.
In a Java program, this means you can invoke on a subclass object any method you can invoke on the superclass object. This is only half of the inheritance story, however, because by default, a subclass also inherits the entire implementation of the superclass. This means that not only ...
Favor Composition Over Inheritance 项目 2012/09/05 Making code reusable through public class inheritance (PCI) is so convenient and easy that to say it should be avoided may sound a bit heretical. After all, isn’t this what OOP is about? And yet that’s the position I hold. To be ...