Docsity

Objects and Classes, Summaries of Object Oriented Programming

Toggle sidebar
bg1
111
4
Objects and Classes
▼
I
NTRODUCTION
TO
O
BJECT
-O
RIENTED
P
ROGRAMMING
▼
U
SING
E
XISTING
C
LASSES
▼
B
UILDING
Y
OUR
O
WN
C
LASSES
▼
S
TATIC
F
IELDS
AND
M
ETHODS
▼
M
ETHOD
P
ARAMETERS
▼
O
BJECT
C
ONSTRUCTION
▼
P
ACKAGES
▼
D
OCUMENTATION
C
OMMENTS
▼
C
LASS
D
ESIGN
H
INTS
T
his chapter will:
• Introduce you to object-oriented programming
• Show you how you can create objects that belong to classes in the standard
Java library
• Show you how to write your own classes
If you do not have a background in object-oriented programming, you will want
to read this chapter carefully. Object-oriented programming requires a different
way of thinking than for procedure-oriented languages. The transition is not
always easy, but you do need some familiarity with object concepts to go further
with Java.
For experienced C++ programmers, this chapter, like the previous chapter, will
present familiar information; however, there are enough differences between the
two languages that you should read the later sections of this chapter carefully.
You’ll find the C++ notes helpful for making the transition.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46

Partial preview of the text

Download Objects and Classes and more Summaries Object Oriented Programming in PDF only on Docsity!

Objects and Classes

 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING  USING EXISTING CLASSES  B UILDING YOUR OWN CLASSES  STATIC FIELDS AND METHODS  METHOD PARAMETERS  OBJECT CONSTRUCTION  PACKAGES  DOCUMENTATION COMMENTS  C LASS DESIGN HINTS

This chapter will:

  • Introduce you to object-oriented programming
  • Show you how you can create objects that belong to classes in the standard Java library
  • Show you how to write your own classes

If you do not have a background in object-oriented programming, you will want to read this chapter carefully. Object-oriented programming requires a different way of thinking than for procedure-oriented languages. The transition is not always easy, but you do need some familiarity with object concepts to go further with Java.

For experienced C++ programmers, this chapter, like the previous chapter, will present familiar information; however, there are enough differences between the two languages that you should read the later sections of this chapter carefully. You’ll find the C++ notes helpful for making the transition.

112 Core Java

Introduction to Object-Oriented Programming

Object-oriented programming (or OOP for short) is the dominant programming paradigm these days, having replaced the “structured,” procedure-based programming techniques that were developed in the early ’70s. Java is totally object oriented, and it is impossible to program it in the procedural style that you may be most comfortable with. We hope this section—especially when combined with the example code supplied in the text and on the CD—will give you enough information about OOP to become productive with Java. Let’s begin with a question that, on the surface, seems to have nothing to do with programming: How did companies like Compaq, Dell, Gateway, and the other major personal computer manufacturers get so big, so fast? Most people would probably say they made generally good computers and sold them at rock-bottom prices in an era when computer demand was skyrocketing. But go further—how were they able to manufacture so many models so fast and respond to the changes that were happening so quickly? Well, a big part of the answer is that these companies farmed out a lot of the work. They bought components from reputable vendors and then assembled them. They often didn’t invest time and money in designing and building power supplies, disk drives, motherboards, and other components. This made it possible for the companies to produce a product and make changes quickly for less money than if they had done the engineering themselves. What the personal computer manufacturers were buying was “prepackaged functionality.” For example, when they bought a power supply, they were buying something with certain properties (size, shape, and so on) and a certain function- ality (smooth power output, amount of power available, and so on). Compaq provides a good example of how effective this operating procedure is. When Compaq moved from engineering most of the parts in their machines to buying many of the parts, they dramatically improved their bottom line. OOP springs from the same idea. Your program is made of objects, with certain properties and operations that the objects can perform. Whether you build an object or buy it might depend on your budget or on time. But, basically, as long as objects satisfy your specifications, you don’t care how the functionality was implemented. In OOP, you only care about what the objects expose. So, just as computer manufacturers don’t care about the internals of a power supply as long as it does what they want, most Java programmers don’t care how an object is implemented as long as it does what they want. Traditional structured programming consists of designing a set of functions (or algorithms ) to solve a problem. After the functions were determined, the

114 Core Java

Encapsulation (sometimes called data hiding) is a key concept in working with objects. Formally, encapsulation is nothing more than combining data and behavior in one package and hiding the implementation of the data from the user of the object. The data in an object are called its instance fields , and the functions and proce- dures that operate on the data are called its methods. A specific object that is an instance of a class will have specific values for its instance fields. The set of those values is the current state of the object. Whenever you apply a method to an object, its state may change. It cannot be stressed enough that 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 the 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 do start writing your own classes in Java, another tenet of OOP makes this easier: classes can be built on other classes. We say that a class that builds on another class extends it. Java, in fact, comes with a “cosmic superclass” called, naturally enough, Object, because it is the factory for all objects. All other classes extend this class. You will see more about the Object class in the next chapter. When you extend an existing class, the new class has all the properties and meth- ods of the class that you extend. You 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.

Objects To work with OOP, you should be able to identify three key characteristics of objects. The three key characteristics are:

  • 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 apply 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 sup- porting 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.

4 • Objects and Classes 115

A change in the state of an object must be a consequence of method calls. (If the object state changed without a method call on that object, someone broke encapsulation.)

However, the state of an object does not completely describe it, since 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 individ- ual objects that are instances of a class always differ in their identity and usu- ally 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.)

In a traditional procedure-oriented 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: You first find classes and then you add methods to each class.

TIP: 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 these nouns are:

  • Item
  • Order
  • Shipping address
  • Payment
  • Account

These nouns may lead to the classes Item, Order, and so on.

Next, one looks 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,” and “apply,” you have to identify the one object that has the major responsibility for carry- ing it out. For example, when a new item is added to an order, the order object should be the one in charge since 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” rule is only a rule of thumb, and only experience can help you decide which nouns and verbs are the important ones when build- ing your classes.

4 • Objects and Classes 117

relationships as arrows with various adornments. Table 4–1 shows the most common UML arrow styles:

Table 4–1: UML notation for class relationships

Figure 4–1 shows an example of a class diagram.

Figure 4–1: A class diagram

Inheritance

Dependency

Aggregation

Association

Directed Association

Relationship UML Connector

118 Core Java

NOTE: The diagram in Figure 4–1 was created using the whiteboard edition of Together/J, a Java application to keep design diagrams and Java code synchronized. You can find the program on the book’s CD-ROM or download it from http://www.togethersoft.com.

Contrasting OOP with Traditional Procedural Programming Techniques We want to end this short introduction to OOP by contrasting OOP with the procedural model that you may be more familiar with. In procedure-oriented programming, you identify the tasks to be performed and then:

  • By a stepwise refinement process, break the task to be performed into subtasks, and these into smaller subtasks, until the subtasks are simple enough to be implemented directly (this is the top-down approach).
  • Write procedures to solve simple tasks and combine them into more sophisticated procedures, until you have the functionality you want (this is the bottom-up approach). Most programmers, of course, use a mixture of the top-down and bottom-up strategies to solve a programming problem. The rule of thumb for discovering procedures is the same as the rule for finding methods in OOP: look for verbs, or actions, in the problem description. The important difference is that in OOP, you first isolate the classes in the project. Only then do you look for the methods of the class. And there is another impor- tant difference between traditional procedures and OOP methods: each method is asso- ciated with the class that is responsible for carrying out the operation. For small problems, the breakdown into procedures works very well. But for larger problems, classes and methods have two advantages. Classes provide a convenient clustering mechanism for methods. A simple Web browser may require 2,000 func- tions for its implementation, or it may require 100 classes with an average of 20 methods per class. The latter structure is much easier to grasp by a programmer. It is also much easier to distribute over a team of programmers. The encapsulation built into classes helps you here as well: classes hide their data representations from all code except their own methods. As Figure 4–2 shows, this means that if a pro- gramming bug messes up data, it is easier to search for the culprit among the 20 methods that had access to that data item than among 2,000 procedures. You may say that this doesn’t sound much different than modularization. You have certainly written programs by breaking the program up into modules that com- municate with each other through procedure calls only, not by sharing data. This (if well done) goes far in accomplishing encapsulation. However, in many programming languages, the slightest sloppiness in programming allows you to get at the data in another module—encapsulation is easy to defeat.

120 Core Java

NOTE: There are many books on UML. We like The Unified Modeling Language User Guide by Grady Booch, Ivar Jacobson, and James Rumbaugh (Addison-Wesley 1999). You can also check out Rational’s Web site for lots of free information about UML (http://www.rational.com/uml). You can find a lighter version of the methodology adapted to both C++ and Java in Practical Object-Oriented Development in C++ and Java , by Cay S. Horstmann (John Wiley & Sons, 1997).

Using Existing Classes

Since you can’t do anything in Java without classes, you have already seen several classes at work. Unfortunately, many of these are quite anomalous in the Java scheme of things. A good example of this is the Math class. You have seen that you can use methods of the Math class, such as Math.random, with- out needing to know how they are implemented—all you need to know is the name and parameters (if any). That is the point of encapsulation and will cer- tainly be true of all classes. Unfortunately, the Math class only encapsulates functionality; it neither needs nor hides data. Since there is no data, you do not need to worry about making objects and initializing their instance fields— there aren’t any! In the next section, we will look at a more typical class, the Date class. You will see how to construct objects and call methods of this class.

Objects and Object Variables To work with objects, you first construct them and specify their initial state. Then you apply methods to the objects. In the Java programming language, you use constructors to construct new instances. A constructor is a special method whose purpose is to construct and initialize objects. Let us look at an example. The standard Java library contains a Date class. Its objects describe points in time, such as “December 31, 1999, 23:59:59 GMT.”

NOTE: You may be wondering: Why use classes to represent dates rather than (as in some languages) a built-in type? For example, Visual Basic has a built-in date type and programmers can specify dates in the format #6/1/1995#. On the sur- face, this sounds convenient—programmers can simply use the built-in date type rather than worrying about classes. But actually, how suitable is the Visual Basic design? In some locales, dates are specified as month/day/year, in others as day/ month/year. Are the language designers really equipped to foresee these kinds of issues? If they do a poor job, the language becomes an unpleasant muddle, but

4 • Objects and Classes 121

unhappy programmers are powerless to do anything about it. By using classes, the design task is offloaded to a library designer. If the class is not perfect, other programmers can easily write their own classes to enhance or replace the system classes.

Constructors always have the same name as the class name. Thus, the constructor for the Date class is called Date. To construct a Date object, you combine the constructor with the new operator, as follows:

new Date()

This expression constructs a new object. The object is initialized to the current date and time.

If you like, you can pass the object to a method:

System.out.println( new Date() );

Alternatively, you can apply a method to the object that you just constructed. One of the methods of the Date class is the toString method. That method yields a string representation of the date. Here is how you would apply the toString method to a newly constructed Date object.

String s = new Date() .toString();

In these two examples, the constructed object is used only once. Usually, you will want to hang on to the objects that you construct so you can keep using them. Simply store the object in a variable:

Date birthday = new Date() ;

Figure 4–3 shows the object variable birthday which refers to the newly con- structed object.

Figure 4–3: Creating a new object

There is an important difference between objects and object variables. For exam- ple, the statement

Date deadline; // deadline doesn’t refer to any object

defines an object variable, deadline, that can refer to objects of type Date. It is important to realize that the variable deadline is not an object and, in fact, does

birthday = Date

4 • Objects and Classes 123

C++ NOTE: Many people mistakenly believe that Java object variables behave like C++ references. But in C++ there are no null references, and references cannot be assigned. You should think of Java object variables as analogous to object pointers in C++. For example, Date birthday; // Java is really the same as Date* birthday; // C++ Once you make this association, everything falls into place. Of course, a Date* pointer isn’t initialized until you initialize it with a call to new. The syntax is almost the same in C++ and Java. Date* birthday = new Date(); // C++ If you copy one variable to another, then both variables refer to the same date—they are point- ers to the same object. The equivalent of the Java null reference is the C++ NULL pointer. All Java objects live on the heap. When an object contains another object variable, that variable still contains just a pointer to yet another heap object. In C++, pointers make you nervous because they are so error-prone. It is easy to create bad pointers or to mess up memory management. In Java, these problems simply go away. If you use an uninitialized pointer, the run-time system will reliably generate a run-time error, instead of producing random results. You don’t worry about memory management because the garbage collector takes care of it. C++ makes quite an effort, with its support for copy constructors and assignment operators, to allow the implementation of objects that copy themselves automatically. For example, a copy of a linked list is a new linked list with the same contents but with an independent set of links. This makes it possible to design classes with the same copy behavior as the built-in types. In Java, you must use the clone method to get a complete copy of an object.

The GregorianCalendar Class of the Java Library

In the preceding examples, we used the Date class that is a part of the standard Java library. An instance of the Date class has a state, namely a particular point in time.

Although you don’t need to know this when you use the Date class, the time is represented by the number of milliseconds (positive or negative) from a fixed point, the so-called epoch , which is 00:00:00 UTC, January 1, 1970. UTC is the Coordinated Universal Time, the scientific time standard that is, for practical purposes, the same as the more familiar GMT or Greenwich Mean Time.

But as it turns out, the Date class is not very useful for manipulating dates. The designers of the Java library take the point of view that a date description such as “December 31, 1999, 23:59:59” is an arbitrary convention, governed by a calendar. This particular description follows the Gregorian calendar, which is the calendar used in most places of the world. The same point in time would be described quite differently in the Chinese or Hebrew lunar calendars, not to mention the calendar used by your customers from Mars.

124 Core Java

NOTE: Throughout human history, civilizations grappled with the design of calendars that attached names to dates and brought order to the solar and lunar cycles. For a fas- cinating explanation of calendars around the world, from the French revolutionary calen- dar to the Mayan long count, see Calendrical Calculations by Nachum Dershowitz and Edward M. Reingold (Cambridge University Press, 1997).

The library designers decided to separate the concerns of keeping time and attaching names to points in time. Therefore, the standard Java library contains two separate classes: the Date class which represents a point in time, and the GregorianCalendar class which expresses dates in the familiar calendar nota- tion. In fact, the GregorianCalendar class extends a more generic Calendar class that describes the properties of calendars in general. In theory, you can extend the Calendar class and implement the Chinese lunar calendar or a Martian calendar. However, the standard library does not contain any calendar implementations besides the Gregorian calendar. Separating time measurement from calendars is good object-oriented design. In general, it is a good idea to use separate classes to express different concepts. The Date class has only a small number of methods that allow you to compare two points in time. For example, the before and after methods tell you if one point in time comes before or after another. if (today.before(birthday)) System.out.println("Still time to shop for a gift.");

NOTE: Actually, the Date class has methods such as getDay, getMonth, and getYear, but these methods are deprecated. A method is deprecated when a library designer realizes that the method should have never been introduced in the first place. These methods were a part of the Date class before the library designers realized that it makes more sense to supply separate calendar classes. When the calendar classes were introduced, the Date methods were tagged as deprecated. You can still use them in your programs, but you will get unsightly compiler warnings if you do. It is a good idea to stay away from using deprecated methods because they may be removed in a future version of the library.

The GregorianCalendar class has many more methods than the Date class. In particular, it has several useful constructors. The expression new GregorianCalendar() constructs a new object that represents the date and time at which the object was constructed.

126 Core Java

If you add a negative number, then the calendar is moved backwards. There is a conceptual difference between the get method on the one hand and the set and add methods on the other hand. The get method only looks up the state of the object and reports on it. The set and add methods modify the state of the object. Methods that change instance fields are called mutator methods and those that only access instance fields without modifying them are called accessor methods.

C++ NOTE: In C++, the const suffix is used to denote accessor methods. A method that is not declared as const is assumed to be a mutator. However, in the Java programming language there is no special syntax to distinguish between accessors and mutators.

A common convention is to prefix accessor methods with the prefix get and mutator methods with the prefix set. For example, the GregorianCalendar class has methods getTime and setTime that get and set the point in time that a calendar object represents. Date time = calendar.getTime(); calendar.setTime(time); These methods are particularly useful to convert between the GregorianCal- endar and Date classes. Here is an example. Suppose you know the year, month, and day and you want to make a Date object with those settings. Since the Date class knows nothing about calendars, first construct a GregorianCalendar object and then call the getTime method to obtain a date: GregorianCalendar calendar = new GregorianCalendar(year, month, day); Date hireDay = calendar.getTime(); Conversely, if you want to find the year, month, or day of a Date object, you con- struct a GregorianCalendar object, set the time, and then call the get method: GregorianCalendar calendar = new GregorianCalendar() calendar.setTime(hireDay); int year = calendar.get(Calendar.YEAR); We will finish this section with a program that puts the GregorianCalendar class to work. The program displays a calendar for the current month, like this: Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19* 20 21 22 23 24 25 26 27 28 29 30 31

4 • Objects and Classes 127

The current day is marked with an *, and the program knows how to compute the days of the week.

Let us go through the key steps of the program. First, we construct a calendar object that is initialized with the current date and time. (We don’t actually care about the time for this application.) GregorianCalendar d = new GregorianCalendar();

We capture the current day and month by calling the get method twice.

int today = d.get(Calendar.DAY_OF_MONTH); int month = d.get(Calendar.MONTH);

Then we set d to the first of the month and get the weekday of that date. d.set(Calendar.DAY_OF_MONTH, 1); int weekday = d.get(Calendar.DAY_OF_WEEK);

The variable weekday is set to 0 if the first day of the month is a Sunday, to 1 if it is a Monday, and so on.

Next, we print the header and the spaces for indenting the first line of the calendar.

For each day, we print a space if the day is < 10, then the day, and then a * if the day equals the current day. Each Saturday, we print a new line.

Then we advance d to the next day: d.add(Calendar.DAY_OF_MONTH, 1);

When do we stop? We don’t know whether the month has 31, 30, 29 or 28 days. Instead, we keep iterating while d is still in the current month. do {

... } while (d.get(Calendar.MONTH) == month);

Once d has moved into the next month, the program terminates.

Example 4–1 shows the complete program.

As you can see, the GregorianCalendar class makes it is simple to write a cal- endar program that takes care of complexities such as weekdays and the varying month lengths. You don’t need to know how the GregorianCalendar class computes months and weekdays. You just use the interface of the class—the get, set, and add methods.

The point of this example program is to show you how you can use the interface of a class to carry out fairly sophisticated tasks, without ever having to know the implementation details.

Example 4–1: CalendarTest.java

  1. import java.util.*;

4 • Objects and Classes 129

  • GregorianCalendar() constructs a calendar object that represents the current time in the default time zone with the default locale.
  • GregorianCalendar(int year, int month, int date) constructs a Gregorian calendar with the given date.
  • GregorianCalendar(int year, int month, int date, int hour, int minutes, int seconds) constructs a Gregorian calendar with the given date and time.
  • boolean equals(Object when) compares this calendar object with when and returns true if the objects represent the same point in time.
  • boolean before(Object when) compares this calendar object with when and returns true if it comes before when.
  • boolean after(Object when) compares this calendar object with when and returns true if it comes after when.
  • int get(int field) gets the value of a particular field.

java.util.GregorianCalendar

Parameters: year^ the year of the date month (^) the month of the date. This value is 0-based; for example, 0 for January date (^) the day of the month

Parameters: year^ the year of the date month (^) the month of the date. This value is 0-based; for example, 0 for January date (^) the day of the month hour (^) the hour (between 0 and 23) minutes (^) the minutes (between 0 and 59) seconds (^) the seconds (between 0 and 59)

Parameters: field^ one of Calendar.ERA, Calendar.YEAR, Calendar.MONTH, Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH, Calendar.DAY_OF_MONTH, Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH,

130 Core Java

  • void set(int field, int value) sets the value of a particular field.
  • void set(int year, int month, int day) sets the date fields to a new date.
  • void set(int year, int month, int day, int hour, int minutes, int seconds) sets the date and time fields to new values.
  • void add(int field, int amount) is a date arithmetic method. Adds the specified amount of time to the given time field. For example, to add 7 days to the current calendar date, call c.add(Calendar.DAY_OF_MONTH, 7).
  • void setTime(Date time) sets this calendar to the given point in time.
  • Date getTime() gets the point in time that is represented by the current value of this calendar object.

Calendar.AM_PM, Calendar.HOUR, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND, Calendar.ZONE_OFFSET, Calendar.DST_OFFSET

Parameters: field^ one of the constants accepted by get value (^) the new value

Parameters: year^ the year of the date month (^) the month of the date. This value is 0-based; for example, 0 for January day (^) the day of the month

Parameters: year^ the year of the date month (^) the month of the date. This value is 0-based; for example, 0 for January day (^) the day of the month hour (^) the hour (between 0 and 23) minutes (^) the minutes (between 0 and 59) seconds (^) the seconds (between 0 and 59)

Parameters: field^ the field to modify (using one of the constants documented in the get method) amount (^) the amount by which the field should be changed (can be negative)

Parameters: time^ a point in time