forked from ChrisMayfield/ThinkJava2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ch11.tex
887 lines (614 loc) · 29.7 KB
/
ch11.tex
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
\chapter{Designing classes}
\index{object!type}
\index{type!object}
Whenever you create a new class, you are creating a new object type with the same name.
So way back in Section~\ref{hello}, when we had the class \java{Hello}, we also had an object type named \java{Hello}.
We didn't declare any variables with type \java{Hello}, and we didn't use \java{new} to create a \java{Hello} object.
It wouldn't have done much good if we had -- but we could have!
In this chapter, you will learn to design classes that represent {\em useful} objects.
Think of a class like a blueprint for a house: you can use the same blueprint to build any number of houses.
Beginners often confuse the difference between classes and objects.
Here are the main ideas:
\begin{itemize}
%\item Defining a {\bf class} creates a new object type with the same name.
\index{class!definition}
\item A {\bf class} definition is a template for objects: it specifies what attributes the objects have and what methods can operate on them.
\index{instance}
\item Every object belongs to some object type; that is, it is an {\bf instance} of some class.
\index{instantiate}
\item The \java{new} operator {\bf instantiates} objects, that is, it creates new instances of a class.
\item The design of a class (what methods it has) determines whether the objects are mutable or immutable.
%\item The methods that operate on an object type are defined in the class for that object.
\end{itemize}
%Think of a class like a blueprint for a house: you can use the same blueprint to build any number of houses.
\section{The Time class}
\index{data encapsulation}
\index{encapsulation!data}
One common reason to define a new class is to encapsulate related data in an object that can be treated as a single unit.
That way, we can use objects as parameters and return values, rather than passing and returning multiple values.
%This design principle is called {\bf data encapsulation}.
We have already seen two types that encapsulate data in this way: \java{Point} and \java{Rectangle}.
\index{class!Time}
\index{Time}
Another example, which we will implement ourselves, is \java{Time}, which represents a time of day.
The data encapsulated in a \java{Time} object include an hour, a minute, and a number of seconds.
Because every \java{Time} object contains these data, we define attributes to hold them.
\index{instance variable}
\index{variable!instance}
Attributes are also called {\bf instance variables}, because each instance has its own variables (as opposed to class variables, coming up in Section~\ref{classvar}).
The first step is to decide what type each variable should be.
It seems clear that \java{hour} and \java{minute} should be integers.
Just to keep things interesting, let's make \java{second} a double.
Instance variables are declared at the beginning of the class definition, outside of any method.
By itself, this code fragment is a legal class definition:
\begin{code}
public class Time {
private int hour;
private int minute;
private double second;
}
\end{code}
\index{private}
\index{variable!private}
The \java{Time} class is \java{public}, which means that it can be used in other classes.
But the instance variables are \java{private}, which means they can only be accessed from inside the \java{Time} class.
If you try to read or write them from another class, you will get a compiler error.
\index{information hiding}
Private instance variables help keep classes isolated from each other so that changes in one class won't require changes in other classes.
It also simplifies what other programmers need to understand in order to use your classes.
This kind of isolation is called {\bf information hiding}.
\section{Constructors}
\index{constructor}
\index{method!constructor}
After declaring instance variables, the next step is to define a {\bf constructor}, which is a special method that initializes the object.
The syntax for constructors is similar to that of other methods, except:
\index{static}
\begin{itemize}
\item The name of the constructor is the same as the name of the class.
\item Constructors have no return type (and no return value).
\item The keyword \java{static} is omitted.
\end{itemize}
Here is an example constructor for the \java{Time} class:
\begin{code}
public Time() {
this.hour = 0;
this.minute = 0;
this.second = 0.0;
}
\end{code}
This constructor does not take any arguments.
Each line initializes an instance variable to zero (which in this example means midnight).
\index{this}
\index{keyword}
The name \java{this} is a keyword that refers to the object we are creating.
You can use \java{this} the same way you use the name of any other object.
For example, you can read and write the instance variables of \java{this}, and you can pass \java{this} as an argument to other methods.
But you do not declare \java{this}, and you can't make an assignment to it.
A common error when writing constructors is to put a \java{return} statement at the end.
Like \java{void} methods, constructors do not return values.
To create a \java{Time} object, you must use the \java{new} operator:
\begin{code}
public static void main(String[] args) {
Time time = new Time();
}
\end{code}
\index{new}
\index{operator!new}
When you use \java{new}, Java creates the object and invokes your constructor to initialize the instance variables.
When the constructor is done, \java{new} returns a reference to the new object.
In this example, the reference gets assigned to the variable \java{time}, which has type \java{Time}.
Figure~\ref{fig.time} shows the result.
\index{memory diagram}
\index{diagram!memory}
\begin{figure}[!ht]
\begin{center}
\includegraphics{figs/time.pdf}
\caption{Memory diagram of a \java{Time} object.}
\label{fig.time}
\end{center}
\end{figure}
\index{recursion!infinite}
\index{infinite recursion}
\index{StackOverflowError}
Beginners sometimes make the mistake of using \java{new} in the constructor.
Doing so causes an infinite recursion, since \java{new} invokes the same constructor, which uses \java{new} again, which invokes the constructor again, and so on.
\begin{code}
public Time() {
new Time(); // StackOverflowError
this.hour = 0;
this.minute = 0;
this.second = 0.0;
}
\end{code}
%If you don't provide a constructor for a class, then Java will generate one for you automatically.
%The default constructor takes no arguments and initializes all attributes to zero (or an equivalent value like \java{false} or \java{null}).
\section{More constructors}
\index{overload}
Like other methods, constructors can be overloaded, which means you can provide multiple constructors with different parameters.
Java knows which constructor to invoke by matching the arguments you provide with the parameters of the constructor.
\index{value constructor}
\index{constructor!value}
It is common to provide a constructor that takes no arguments, like the previous one, and a ``value constructor'', like this one:
\begin{code}
public Time(int hour, int minute, double second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
\end{code}
\index{shadow}
All this constructor does is copy values from the parameters to the instance variables.
In this example, the names and types of the parameters are the same as the instance variables.
As a result, the parameters {\bf shadow} (or hide) the instance variables, so the keyword \java{this} is necessary to tell them apart.
Parameters don't have to use the same names, but that's a common style.
To invoke this second constructor, you have to provide arguments after the \java{new} operator.
This example creates a \java{Time} object that represents a fraction of a second before noon:
\begin{code}
Time time = new Time(11, 59, 59.9);
\end{code}
Overloading constructors provides the flexibility to create an object first and then fill in the attributes, or collect all the information before creating the object itself.
Once you get the hang of it, writing constructors gets boring.
You can write them quickly just by looking at the list of instance variables.
In fact, some IDEs can generate them for you.
Pulling it all together, here is the complete class definition so far:
\index{Time.java}
\begin{trinket}{Time.java}
public class Time {
private int hour;
private int minute;
private double second;
public Time() {
this.hour = 0;
this.minute = 0;
this.second = 0.0;
}
public Time(int hour, int minute, double second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
}
\end{trinket}
\section{Getters and setters}
Recall that the instance variables of \java{Time} are \java{private}.
We can access them from within the \java{Time} class, but if we try to access them from another class, the compiler reports an error.
\index{private}
\index{variable!private}
A class that uses objects defined in another class is called a {\bf client}.
For example, here is a new class called \java{TimeClient}.
\index{client}
\begin{code}
public class TimeClient {
public static void main(String[] args) {
Time time = new Time(11, 59, 59.9);
System.out.println(time.hour); // compiler error
}
}
\end{code}
If you try to compile this code, you will get an error message like ``hour has private access in Time''.
There are three ways to solve this problem:
\begin{itemize}
\item We could make the instance variables \java{public}.
\item We could provide methods to access the instance variables.
\item We could decide that it's not a problem, and refuse to let other classes access the instance variables.
\end{itemize}
The first choice is appealing because it's simple.
But here is the problem: when Class $A$ accesses the instance variables of Class $B$ directly, $A$ becomes dependent on $B$.
If anything in $B$ changes later, it is likely that $A$ will have to change, too.
\index{dependent}
\index{independent}
But if $A$ only uses methods to interact with $B$, $A$ and $B$ are less dependent, which means that we can make changes in $B$ without affecting $A$ (as long as we don't change the method parameters).
So if we decide that \java{TimeClient} should be able to read the instance variables of \java{Time}, we should provide methods to do it:
\begin{code}
public int getHour() {
return this.hour;
}
public int getMinute() {
return this.minute;
}
public double getSecond() {
return this.second;
}
\end{code}
\index{accessor}
\index{method!accessor}
\index{getter}
\index{method!getter}
Methods like these are formally called ``accessors'', but more commonly referred to as {\bf getters}.
By convention, the method that gets a variable named \java{something} is called \java{getSomething}.
If we decide that \java{TimeClient} should also be able to modify the instance variables of \java{Time}, we can provide methods to do that, too:
\begin{code}
public void setHour(int hour) {
this.hour = hour;
}
public void setMinute(int minute) {
this.minute = minute;
}
public void setSecond(double second) {
this.second = second;
}
\end{code}
\index{mutator}
\index{method!mutator}
\index{setter}
\index{method!setter}
These methods are formally called ``mutators'', but more commonly known as {\bf setters}.
The naming convention is similar; the method that sets \java{something} is usually called \java{setSomething}.
Writing getters and setters can get boring, but many IDEs can generate them for you based on the instance variables.
\section{Displaying objects}
If you create a \java{Time} object and display it with \java{println}:
\begin{code}
public static void main(String[] args) {
Time time = new Time(11, 59, 59.9);
System.out.println(time);
}
\end{code}
\index{print}
\index{statement!print}
\index{object!displaying}
The output will look something like:
\begin{stdout}
Time@80cc7c0
\end{stdout}
\index{address}
\index{hexadecimal}
When Java displays the value of an object type, it displays the name of the type and the address of the object (in hexadecimal).
This address can be useful for debugging, if you want to keep track of individual objects.
To display \java{Time} objects in a way that is more meaningful to users, you could write a method to display the hour, minute, and second.
Using \java{printTime} in Section~\ref{stack} as a starting point, we could write:
\begin{code}
public static void printTime(Time t) {
System.out.print(t.hour);
System.out.print(":");
System.out.print(t.minute);
System.out.print(":");
System.out.println(t.second);
}
\end{code}
The output of this method, given the \java{time} object from the first example, would be {\tt 11:59:59.9}.
We can use \java{printf} to make the code more concise:
\index{printf}
\index{print statement}
\index{format string}
\begin{code}
public static void printTime(Time t) {
System.out.printf("%02d:%02d:%04.1f\n",
t.hour, t.minute, t.second);
}
\end{code}
As a reminder, you need to use \java{\%d} with integers and \java{\%f} with floating-point numbers.
The \java{02} option means ``total width 2, with leading zeros if necessary'', and the \java{04.1} option means ``total width 4, one digit after the decimal point, leading zeros if necessary''.
The output is the same: {\tt 11:59:59.9}.
\section{The toString method}
\index{toString}
\index{method!toString}
Every object type has a method called \java{toString} that returns a string representation of the object.
When you display an object using \java{print} or \java{println}, Java invokes the object's \java{toString} method.
\index{override}
By default it simply displays the type of the object and its address, but you can {\bf override} this behavior by providing your own \java{toString} method.
For example, here is a \java{toString} method for \java{Time}:
\begin{code}
public String toString() {
return String.format("%02d:%02d:%04.1f\n",
this.hour, this.minute, this.second);
}
\end{code}
\index{instance method}
\index{method!instance}
The definition does not have the keyword \java{static}, because it is not a static method.
It is an {\bf instance method}, so called because when you invoke it, you invoke it on an instance of the class (\java{Time} in this case).
Instance methods are sometimes called ``non-static''; you might see this term in an error message.
The body of the method is similar to \java{printTime} in the previous section, with two changes:
\begin{itemize}
\item Inside the method, we use \java{this} to refer to the current instance; that is, the object the method is invoked on.
\item Instead of \java{printf}, it uses \java{String.format}, which returns a formatted \java{String} rather than displaying it.
\end{itemize}
\index{string!format}
Now you can call \java{toString} directly:
\begin{code}
Time time = new Time(11, 59, 59.9);
String s = time.toString();
\end{code}
Or you can invoke it indirectly through \java{println}:
\begin{code}
System.out.println(time);
\end{code}
In this example, \java{this} in \java{toString} refers to the same object as \java{time}.
The return value is \java{"11:59:59.9"}.
\section{The equals method}
\label{equals}
\index{== equals operator}
\index{equals}
\index{method!equals}
We have seen two ways to check whether values are equal: the \java{==} operator and the \java{equals} method.
With objects you can use either one, but they are not the same.
\begin{itemize}
\index{identical}
\item The \java{==} operator checks whether two references are {\bf identical}; that is, whether they refer to the same object.
\index{equivalent}
\item The \java{equals} method checks whether two objects are {\bf equivalent}; that is, whether they have the same values.
\end{itemize}
The definition of identity is always the same, so the \java{==} operator always does the same thing.
But the definition of equivalence is different for different objects, so objects can define their own \java{equals} methods.
Consider the following variables and the memory diagram in Figure~\ref{fig.time2}.
\begin{code}
Time time1 = new Time(9, 30, 0.0);
Time time2 = time1;
Time time3 = new Time(9, 30, 0.0);
\end{code}
\index{memory diagram}
\index{diagram!memory}
\begin{figure}[!ht]
\begin{center}
\includegraphics{figs/time2.pdf}
\caption{Memory diagram of three \java{Time} variables.}
\label{fig.time2}
\end{center}
\end{figure}
The assignment operator copies references, so \java{time1} and \java{time2} refer to the same object.
Because they are identical, \java{time1 == time2} is true.
But \java{time1} and \java{time3} refer to two different objects.
Because they are not identical, \java{time1 == time3} is false.
By default, the \java{equals} method does the same thing as \java{==}.
For \java{Time} objects, that's probably not what we want.
For example, \java{time1} and \java{time3} represent the same time of day, so we should consider them equivalent.
\index{equals}
\index{method!equals}
We can provide an \java{equals} method that implements this idea:
\begin{code}
public boolean equals(Time that) {
return this.hour == that.hour
&& this.minute == that.minute
&& this.second == that.second;
}
\end{code}
\java{equals} is an instance method, so it doesn't have the keyword \java{static}.
It uses \java{this} to refer to current object, and \java{that} to refer to the other.
The parameter named \java{that} is not a keyword and could have a different name, but it improves readability.
We can invoke \java{equals} as follows:
\begin{code}
time1.equals(time3);
\end{code}
Inside the \java{equals} method, \java{this} refers to the same object as \java{time1}, and \java{that} refers to the same object as \java{time3}.
Since their instance variables are equal, the result is \java{true}.
Many objects have a similar notion of equivalence; that is, two objects are considered equal if their instance variables are equal.
But other definitions are possible.
You could, for example, allow a \java{Time} object and a \java{String} object to be considered equal if they represent the same time.
\begin{code}
public boolean equals(String str) {
return str.equals(this.toString());
}
\end{code}
The \java{equals} method is now overloaded.
If we invoke \java{time1.equals(time3)}, the first method will be used; \java{time1.equals("09:30:00.0")} uses the second.
\section{Adding times}
Suppose you are going to a movie that starts at 18:50 (or 6:50 PM), and the running time is 2 hours 16 minutes.
What time does the movie end?
We'll use \java{Time} objects to figure it out.
\begin{code}
Time startTime = new Time(18, 50, 0.0);
Time runningTime = new Time(2, 16, 0.0);
\end{code}
\index{Time!addition}
\index{addition!time}
Here are two ways we could ``add'' the \java{Time} objects:
\begin{itemize}
\item We could write a static method that takes two \java{Time} objects as parameters (not object-oriented).
\item We could write an instance method that gets invoked on one object and takes the other as a parameter.
\end{itemize}
To demonstrate the difference, we'll do both.
Here is a simple version that uses the static approach:
\index{static}
\index{method!static}
\begin{code}
public static Time add(Time t1, Time t2) {
Time sum = new Time();
sum.hour = t1.hour + t2.hour;
sum.minute = t1.minute + t2.minute;
sum.second = t1.second + t2.second;
return sum;
}
\end{code}
And here's how we would invoke the static method:
\begin{code}
Time endTime = Time.add(startTime, runningTime);
\end{code}
On the other hand, here's what it looks like as an instance method:
\index{instance method}
\index{method!instance}
\begin{code}
public Time add(Time t2) {
Time sum = new Time();
sum.hour = this.hour + t2.hour;
sum.minute = this.minute + t2.minute;
sum.second = this.second + t2.second;
return sum;
}
\end{code}
The changes are:
\begin{itemize}
\item We removed the keyword \java{static}.
\item We removed the first parameter.
\item We replaced \java{t1} with \java{this}.
\end{itemize}
%Optionally, you could replace \java{t2} with \java{that}.
%Unlike \java{this}, \java{that} is not a keyword; it's just a slightly clever variable name.
And here's how we would invoke the instance method:
\begin{code}
Time endTime = startTime.add(runningTime);
\end{code}
That's all there is to it.
Static methods and instance methods do the same thing, and you can convert from one to the other with just a few changes.
There's only one problem: the addition code itself is not correct.
For this example, it returns {\tt 20:66}, which is not a valid time.
If \java{second} exceeds 59, we have to ``carry'' into the minutes column, and if \java{minute} exceeds 59, we have to carry into \java{hour}.
Here is a better version of \java{add}:
\begin{code}
public Time add(Time t2) {
Time sum = new Time();
sum.hour = this.hour + t2.hour;
sum.minute = this.minute + t2.minute;
sum.second = this.second + t2.second;
if (sum.second >= 60.0) {
sum.second -= 60.0;
sum.minute += 1;
}
if (sum.minute >= 60) {
sum.minute -= 60;
sum.hour += 1;
}
return sum;
}
\end{code}
It's still possible that \java{hour} may exceed 23, but there's no \java{days} attribute to carry into.
In that case, \java{sum.hour -= 24} would yield the correct result.
\section{Pure methods}
This implementation of \java{add} does not modify either of the parameters.
Instead, it creates and returns a new \java{Time} object.
Alternatively, we could have written a method like this:
\begin{code}
public void increment(double seconds) {
this.second += seconds;
while (this.second >= 60.0) {
this.second -= 60.0;
this.minute += 1;
}
while (this.minute >= 60) {
this.minute -= 60;
this.hour += 1;
}
}
\end{code}
The \java{increment} method modifies an existing \java{Time} object.
It doesn't create a new one, and it doesn't return anything.
\index{pure method}
\index{method!pure}
In contrast, methods like \java{add} (in the previous section) are called {\bf pure} because:
\begin{itemize}
\item They don't modify the parameters.
\item They don't have any other ``side effects'', like printing.
\item The return value only depends on the parameters, not on any other data.
\end{itemize}
\index{modifier method}
\index{method!modifier}
Methods like \java{increment}, which breaks the first rule, are sometimes called {\bf modifiers}.
They are usually void methods, but sometimes they return a reference to the object they modify.
Modifiers can be more efficient because they don't create new objects.
But they can also be error-prone.
When objects are aliased, the effects of modifiers can be confusing.
%As a general rule, if you are using modifiers, you should avoid aliasing.
\index{immutable}
If a class provides only getters and pure methods (no setters or modifiers), then the objects will be immutable.
Working with immutable objects can be more difficult at first, but they can save you from long hours of debugging.
\section{Vocabulary}
\begin{description}
\term{class}
Previously, we defined a class as a collection of related methods.
Now you know that a class is also a template for a new type of object.
\term{instance}
A member of a class.
Every object is an instance of some class.
\term{instantiate}
Create a new instance of a class in the computer's memory.
%\term{data encapsulation}
%A technique for bundling multiple named variables into a single object.
\term{instance variable}
An attribute of an object; a non-static variable defined at the class level.
\term{information hiding}
The practice of making instance variables \java{private} to limit dependencies between classes.
\term{constructor}
A special method that initializes the instance variables of a newly-constructed object.
\term{shadow}
Defining a local variable or parameter with the same name and type as an instance variable.
\term{client}
A class that uses objects defined in another class.
\term{getter}
A method that returns the value of an instance variable.
\term{setter}
A method that assigns a value to an instance variable.
\term{override}
Replacing a default implementation of a method, such as \java{toString}.
\term{instance method}
A non-static method that has access to \java{this} and the instance variables.
\term{identical}
Two values that are the same; in the case of objects, two variables that refer to the same object.
\term{equivalent}
Two objects that are ``equal'' but not necessarily identical, as defined by the \java{equals} method.
\term{pure method}
A static method that depends only on its parameters and no other data.
\term{modifier method}
A method that changes the state (instance variables) of an object.
\end{description}
\section{Exercises}
The code for this chapter is in the {\tt ch11} directory of {\tt ThinkJavaCode2}.
See page~\pageref{code} for instructions on how to download the repository.
Before you start the exercises, we recommend that you compile and run the examples.
\begin{exercise} %%V6 Ex11.1
Review the documentation of \java{java.awt.Rectangle}.
Which methods are pure?
Which are modifiers?
If you review the documentation of \java{java.lang.String}, you should see that there are no modifiers, because strings are immutable.
\end{exercise}
\begin{exercise} %%V6 Ex11.2
The implementation of \java{increment} in this chapter is not very efficient.
Can you rewrite it so it doesn't use any loops?
{\it Hint:} Remember the remainder operator. And yes, it works with \java{double}s too.
\end{exercise}
\begin{exercise} %%V6 Ex11.3
\index{Scrabble}
In the board game Scrabble, each tile contains a letter, which is used to spell words in rows and columns, and a score, which is used to determine the value of words.
\begin{enumerate}
\item Write a definition for a class named \java{Tile} that represents Scrabble tiles.
The instance variables should include a character named \java{letter} and an integer named \java{value}.
\item Write a constructor that takes parameters named \java{letter} and \java{value} and initializes the instance variables.
\item Write a method named \java{printTile} that takes a \java{Tile} object as a parameter and displays the instance variables in a reader-friendly format.
\item Write a method named \java{testTile} that creates a \java{Tile} object with the letter \java{Z} and the value \java{10}, and then uses \java{printTile} to display the state of the object.
\item Implement the \java{toString} and \java{equals} methods for a \java{Tile}.
\item Create getters and setters for each of the attributes.
\end{enumerate}
The point of this exercise is to practice the mechanical part of creating a new class definition.
\end{exercise}
\begin{exercise} %%V6 Ex11.4
Write a class definition for \java{Date}, an object type that contains three integers: \java{year}, \java{month}, and \java{day}.
This class should provide two constructors.
The first should take no parameters and initialize a default date.
The second should take parameters named \java{year}, \java{month} and \java{day}, and use them to initialize the instance variables.
Write a \java{main} method that creates a new \java{Date} object named \java{birthday}.
The new object should contain your birth date.
You can use either constructor.
%Compare your implementation to \java{java.util.Date}.
\end{exercise}
\begin{exercise} %%V6 Ex11.5
\index{rational number}
A rational number is a number that can be represented as the ratio of two integers.
For example, $2/3$ is a rational number, and you can think of 7 as a rational number with an implicit 1 in the denominator.
%The goal of this exercise is to write a class definition for rational numbers.
\begin{enumerate}
\item Define a class called \java{Rational}.
A \java{Rational} object should have two integer instance variables that store the numerator and denominator.
\item Write a constructor that takes no arguments and that sets the numerator to 0 and denominator to 1.
\item Write an instance method called \java{printRational} that displays a \java{Rational} in some reasonable format.
\item Write a \java{main} method that creates a new object with type \java{Rational}, sets its instance variables to some values, and displays the object.
\item At this stage, you have a minimal testable program.
Test it and, if necessary, debug it.
\item Write a \java{toString} method for \java{Rational} and test it using \java{println}.
\item Write a second constructor that takes two arguments and uses them to initialize the instance variables.
\item Write an instance method called \java{negate} that reverses the sign of a rational number.
This method should be a modifier, so it should be void.
Add lines to \java{main} to test the new method.
\item Write an instance method called \java{invert} that inverts the number by swapping the numerator and denominator.
It should be a modifier.
Add lines to \java{main} to test the new method.
\item Write an instance method called \java{toDouble} that converts the rational number to a \java{double} (floating-point number) and returns the result.
This method is a pure method; it does not modify the object.
As always, test the new method.
\item Write an instance method named \java{reduce} that reduces a rational number to its lowest terms by finding the greatest common divisor (GCD) of the numerator and denominator and dividing through.
This method should be a pure method; it should not modify the instance variables of the object on which it is invoked.
{\it Hint:} Finding the GCD only takes a few lines of code.
Search the web for ``Euclidean algorithm''.
\item Write an instance method called \java{add} that takes a \java{Rational} number as an argument, adds it to \java{this}, and returns a new \java{Rational} object.
There are several ways to add fractions.
You can use any one you want, but you should make sure that the result of the operation is reduced so that the numerator and denominator have no common divisor (other than 1).
\end{enumerate}
The purpose of this exercise is to write a class definition that includes a variety of methods, including constructors, static methods, instance methods, modifiers, and pure methods.
\end{exercise}