摘抄《Java编程思想:复用类》

 中午完成了第七章复用类的初步学习,这是第一次这么用心看这本书,以前可能会认真的记住知识点,但是感觉现在才是刚刚入门编程的世界。知识点是必须要牢记的这是基本,但是也要更加注意编程思想,这不仅对于技术有提高,对于生活和做事也有类似的哲学效应。感谢Brucel Eckel的指导。

以下内容是7.10总结原文,现摘抄下来时常温习:

=====================================

继承和组合都能从现有类型生成新类型。组合一般是将现有类型作为新类型底层实现的一部分来加以复用,而继承复用的是接口

Both inheritance and composition allow you to create a new type from existing types.Composition reuses existing types as part of the underlying implementation of the new type,and inheritance reuses the interface.

在使用继承时,由于导出类具有基类接口,因此它可以向上转型至基类,这对于多态来讲至关重要,就像我们将在下一章中将要看到的那样。

With Inheritance, the derived class has the base-class interface, so it can be upcast to the base, which is critical for polymorphism, as you’ll see in the next chapter.

尽管面向对象编程对继承极力强调,但在开始一个设计时,一般优先选择使用组合(或者可能是代理),只在确定必要时才使用继承。因为组合更具灵活性。此外,通过对成员类型使用继承技术的添加技巧,可以在运行时改变那些成员对象的类型和行为。因此,可以在运行时改变组合而成的对象的行为。

Despite the strong emphasis on inheritance in object-oriented programming, when you start a design you should generally prefer composition (or possibly delegation) during the first cut and use inheritance only when it is clearly necessary. Composition tends to be more flexible. In addition, by using the added artifice of inheritance with your member type, you can change the exact type, and thus the behavior, of those member objects at run time. Therefore, you can change the behavior of the composed object at run time.

在设计一个系统时,目标应该是找到或创建某些类,其中每个类都有具体的用途,而且既不会太大(包含太多功能而难以复用),也不会因为太小(不添加其他功能就无法使用)。如果你的设计变得过于复杂,通过将现有类拆分为更小的部分而添加更多的对象,通常会有所帮助。

When designing a system, your goal is to find or create a set of classes in which each class has a specific use and is neither too big (encompassing so much functionality that it’s unwieldy to reuse) nor annoyingly small (you can’t use it by itself or without adding functionality). If your designs become too complex, it’s often helpful to add more objects by breaking down existing ones into smaller parts.

当你开始设计一个系统时,应该认识到程序开发是一种增量过程,犹如人类的学习一样,这一点很重要。程序开发依赖于实验,你可以尽己所能的去分析,但当你开始执行一个项目时,你仍然无法知道所有的答案。如果将项目视作是一种有机的、进化着的生命体而去培养,而不是打算像该摩天大楼一样快速见效,就会获得更多的成功和更迅速的回馈。继承与组合正是在面向对象程序设计中使得你可以执行这种实验的最基本的两个工具。

When you set out to design a system, it’s important to realize that program development is an incremental process, just like human learning. It relies on experimentation; you can do as much analysis as you want, but you still won’t know all the answers when you set out on a project. You’ll have much more success-and more immediate feedback-if you start out to “grow” your project as an organic, evolutionary creature, rather than constructing it all at once like a glass-box skyscraper. Inheritance and composition are two of the most fundamental tools in object-oriented programming that allow you to perform such experiments.