Core Java Volume I — 4.1. Introduction to Object-Oriented Programming
4.1. Introduction to Object-Oriented Programming
Object-oriented programming, or OOP for short, is the dominant programming paradigm these days, having replaced the "structured," procedural programming techniques that were developed in the 1970s. Since Java is object-oriented, you have to be familiar with OOP to become productive with Java.
An object-oriented program is made of objects. Each object has a specific functionality, exposed to its users, and a hidden implementation. Many objects in your programs will be taken "off-the-shelf" from a library; others will be custom-designed.
Whether you build an object or buy it might depend on your budget or on time. But, basically, as long as an object satisfies your specifications, you don't care how the functionality is implemented.
Traditional structured programming consists of designing a set of procedures (or algorithms) to solve a problem. Once the procedures are determined, the traditional next step was to find appropriate ways to store the data. This is why the designer of the Pascal language, Niklaus Wirth, called his famous book on programming Algorithms + Data Structures = Programs (Prentice Hall, 1975). Notice that in Wirth's title, algorithms come first, and data structures come second. This mimics the way programmers worked at that time. First, they decided on the procedures for manipulating the data; then, they decided what structure to impose on the data to make the manipulations easier. OOP reverses the order: puts the data first, then looks at the algorithms to operate on the data.
For small problems, the breakdown into procedures works very well. But objects are more appropriate for larger problems. Consider a simple web browser. It might require 2,000 procedures for its implementation, all of which manipulate a set of global data. In the object-oriented style, there might be 100 classes with an average of 20 methods per class (see Figure 4.1). This structure is much easier for a programmer to grasp. It is also much easier to find bugs in. Suppose the data of a particular object is in an incorrect state. It is far easier to search for the culprit among the 20 methods that had access to that data item than among 2,000 procedures.
4.1.1. Classes
A class is the template or blueprint from which objects are made. Think about classes as cookie cutters. Objects are the cookies themselves. When you construct an object from a class, you are said to have created an instance of the class(由类构造(construct)对象的过程称为创建类的实例(instance)).
As you have seen, all code that you write in Java is inside a class. The standard Java library supplies several thousand classes for such diverse purposes as user interface design, dates and calendars, and network programming. Nonetheless, in Java you still have to create your own classes to describe the objects of your application's problem domain.
Encapsulation (sometimes called information hiding) is a key concept in working with objects. Formally, encapsulation is simply combining data and behavior in one package and hiding the implementation details from the users of the object. The bits of data in an object are called its instance fields, and the procedures that operate on the data are called its methods(对象中的数据称为实例域,操作数据的过程称为方法). A specific object that is an instance of a class will have specific values of its instance fields. The set of those values is the current state of the object.
Whenever you invoke a method on an object, its state may change.
The key to making encapsulation work is to have methods never directly access instance fields in a class other than their own(实现封装的关键在于绝对不能让类中的方法直接地访问其他类的实例域). Programs should interact with object data only through the object's methods. Encapsulation is the way to give an object its "black box" behavior, which is the key to reuse and reliability. This means a class may totally change how it stores its data, but as long as it continues to use the same methods to manipulate the data, no other object will know or care.
When you start writing your own classes in Java, another tenet of OOP will make this easier: Classes can be built by extending other classes. Java, in fact, comes with a "cosmic superclass" called Object. All other classes extend this class. You will learn more about the Object class in the next chapter.
When you extend an existing class, the new class has all the properties and methods of the class that you extend. You then supply new methods and data fields that apply to your new class only. The concept of extending a class to obtain another class is called inheritance. See the next chapter for details on inheritance.
4.1.2. Objects
To work with OOP, you should be able to identify three key characteristics of objects(使用OOP一定要清楚对象的三个主要特征):
- The object's behavior(对象的行为)—What can you do with this object, or what methods can you apply to it?
- The object's state(对象的状态)—How does the object react when you invoke those methods?
- The object's identity(对象标识)—How is the object distinguished from others that may have the same behavior and state?
All objects that are instances of the same class share a family resemblance by supporting the same behavior. The behavior of an object is defined by the methods that you can call.
Next, each object stores information about what it currently looks like. This is the object's state. An object's state may change over time, but not spontaneously. A change in the state of an object must be a consequence of method calls. (If an object's state changed without a method call on that object, someone broke encapsulation.)
However, the state of an object does not completely describe it, because each object has a distinct identity. For example, in an order processing system, two orders are distinct even if they request identical items. Notice that the individual objects that are instances of a class always differ in their identity and usually differ in their state.
These key characteristics can influence each other. For example, the state of an object can influence its behavior. (If an order is "shipped" or "paid," it may reject a method call that asks it to add or remove items. Conversely, if an order is "empty"—that is, no items have yet been ordered—it should not allow itself to be shipped.)
4.1.3. Identifying Classes
In a traditional procedural program, you start the process at the top, with the main function. When designing an object-oriented system, there is no "top," and newcomers to OOP often wonder where to begin. The answer is, identify your classes and then add methods to each class.
A simple rule of thumb in identifying classes is to look for nouns in the problem analysis. Methods, on the other hand, correspond to verbs.
For example, in an order-processing system, some of the nouns are
- Item
- Order
- Shipping address
- Payment
- Account
These nouns may lead to the classes Item, Order, and so on.
Next, look for verbs. Items are added to Orders. Orders are shipped or canceled. Payments are applied to Orders. With each verb, such as "add," "ship," "cancel," or "apply," you identify the object that has the major responsibility for carrying it out. For example, when a new item is added to an order, the order object should be the one in charge because it knows how it stores and sorts items. That is, add should be a method of the Order class that takes an Item object as a parameter.
Of course, the "noun and verb" is but a rule of thumb; only experience can help you decide which nouns and verbs are the important ones when building your classes.
4.1.4. Relationships between Classes
The most common relationships between classes are(在类之间,最常见的关系有):
- Dependence ("uses–a"):依赖
- Aggregation ("has–a"):聚合
- Inheritance ("is–a"):继承
The dependence, or "uses–a" relationship(依赖:“uses-a”关系), is the most obvious and also the most general. For example, the Order class uses the Account class because Order objects need to access Account objects to check for credit status. But the Item class does not depend on the Account class, because Item objects never need to worry about customer
accounts. Thus, a class depends on another class if its methods use or manipulate objects of that class.
Try to minimize the number of classes that depend on each other. The point is, if a class A is unaware of the existence of a class B, it is also unconcerned about any changes to B. (And this means that changes to B do not introduce bugs into A.) In software engineering terminology, you want to minimize the coupling between classes.
The aggregation, or "has–a" relationship(聚合:“has-a”关系), is easy to understand because it is concrete; for example, an Order object contains Item objects. Containment means that objects of class A contain objects of class B.
The inheritance, or "is–a" relationship(继承:“is-a”关系), expresses a relationship between a more special and a more general class. For example, a RushOrder class inherits from an Order class. The specialized RushOrder class has special methods for priority handling and a different method for computing shipping charges, but its other methods, such as adding items and billing, are inherited from the Order class. In general, if class A extends class B, class A inherits methods from class B but has more capabilities. (We describe inheritance more fully in the next chapter, in which we discuss this important notion at some length.)
Many programmers use the UML (Unified Modeling Language) notation to draw class diagrams that describe the relationships between classes. You can see an example of such a diagram in Figure 4.2. You draw classes as rectangles, and relationships as arrows with various adornments. Table 4.1 shows the most common UML arrow styles.
Core Java Volume I — 4.1. Introduction to Object-Oriented Programming的更多相关文章
- Core Java Volume I — 1.2. The Java "White Paper" Buzzwords
1.2. The Java "White Paper" BuzzwordsThe authors of Java have written an influential White ...
- Core Java Volume I — 4.7. Packages
4.7. PackagesJava allows you to group classes in a collection called a package. Packages are conveni ...
- Core Java Volume I — 3.10. Arrays
3.10. ArraysAn array is a data structure that stores a collection of values of the same type. You ac ...
- Core Java Volume I — 3.8. Control Flow
3.8. Control FlowJava, like any programming language, supports both conditional statements and loops ...
- Core Java Volume I — 5.1. Classes, Superclasses, and Subclasses
5.1. Classes, Superclasses, and SubclassesLet's return to the Employee class that we discussed in th ...
- Core Java Volume I — 4.10. Class Design Hints
4.10. Class Design HintsWithout trying to be comprehensive or tedious, we want to end this chapter w ...
- Core Java Volume I — 4.6. Object Construction
4.6. Object ConstructionYou have seen how to write simple constructors that define the initial state ...
- Core Java Volume I — 4.5. Method Parameters
4.5. Method ParametersLet us review the computer science terms that describe how parameters can be p ...
- Core Java Volume I — 4.4. Static Fields and Methods
4.4. Static Fields and MethodsIn all sample programs that you have seen, the main method is tagged w ...
随机推荐
- 电脑的基本硬件知识以及unix图解
1.DELL R720 R610 2.电源: 人体心脏3.硬盘: 存数据的地方.机械的性能不高,3.5英寸 性能 SATA 借口<SAS <SSD 价格:SSD> SAS>SA ...
- list列表类型
list类型最典型的应用场景是做队列,相当于C#中的Queue(一般用ConcurrentQueue)队列. 我们可以使用lpush,lpop,rpush,rpop这四个命令来实现,如下图.
- ruby学习网站
Ruby官方中文网(推荐): https://www.ruby-lang.org/zh_cn/ 国内非常不错的Ruby学习教程网站(推荐): http://www.yiibai.com/ruby Ru ...
- 编写自己的Windows Live Writer插件
起因 自从小猪使用Windows Live Writer(wlw)来写博客之后就很少打开网站的后台编辑器了,这真是个写博客的好东西啊,但是任何东西都是不完美的.索契冬奥会开幕式都会把五环弄成四环呢!对 ...
- Flickr 网站架构分析
Flickr 网站架构分析 Flickr.com 是网上最受欢迎的照片共享网站之一,还记得那位给Windows Vista拍摄壁纸的Hamad Darwish吗?他就是将照片上传到Flickr,后而被 ...
- "QQ尾巴病毒"核心技术的实现原理分析
声明:本文旨在探讨技术,请读者不要使用文章中的方法进行任何破坏. 2003这一年里,QQ尾巴病毒可以算是风光了一阵子.它利用IE的邮件头漏洞在QQ上疯狂传播.中毒者在给别人发信息时,病毒会自动在信息文 ...
- Codeforces 235C
题目大意: 给定一个字符串,接下来再给n个字符串,求原字符串中含有多少个当前给定字符串的循环同构体的字符串的个数 以初始字符串构建后缀自动机,在自动机上前进的时候,比如当前需要匹配的字符串为aba,到 ...
- Program A-归并排序
Description In this problem, you have to analyze a particular sorting algorithm. The algorithm proce ...
- ACM - 概率、期望题目 小结(临时)
概率DP求期望大多数都是全期望公式的运用.主要思考状态空间的划分以及状态事件发生的概率.问题可以分为无环和有环两类.无环一类多数比较简单,可以通过迭代或者记忆化搜索完成.有环一类略复杂,可以通过假设方 ...
- QT5.4关联VS2010,配置VAssistX关联Qt类
1.参考网站:http://www.kavenblog.com/?p=272 2.下载插件:http://www.qt.io/zh-hans/download-open-source/#section ...