-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassesObjects.tex
More file actions
991 lines (826 loc) · 39.4 KB
/
classesObjects.tex
File metadata and controls
991 lines (826 loc) · 39.4 KB
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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
\chapter{Classes and objects}
\label{ch:classesObjects}
\index{object-oriented}
\index{class-oriented@``class-oriented''}
Java is called an ``object-oriented'' programming language. Now if \textit{I}
were King of the World, I would have called it a ``\textit{class}-oriented''
language instead. That's because in Java, you don't write code for objects,
but for \textit{classes}, and the code then defines the behavior of the
objects that are based on them.\footnote{There are other languages, for
instance JavaScript (no relation to Java), which do IMO deserve the term
``\textit{object}-oriented,'' since you can create code for individual objects
rather than classes, and not every object has to have a class at all.} You'll
sometimes hear people mistakenly say stuff like, ``I wrote some code for the
DatabaseConnection object today.'' It makes me wince. They weren't writing
``code for the object,'' but the code for a class.
\section{Terms}
\index{object}
\index{class@\texttt{class}}
\index{Venkman, Peter}
So here's a crucial pair of definitions. A \textbf{class} is a
\textit{category} of things. An \textbf{object} is a concrete \textit{example}
of a class. If ``University'' is a class, then ``UMW'' is an object; if
``Course'' is a class, then ``CPSC 240'' is an object. The difference is real,
and it is vitally important to keep at the forefront of your mind as you begin
your OO quest. Getting them mixed up is like Peter Venkman crossing the
streams.
\index{template}
\index{modeling}
You'll sometimes hear alternate definitions of these terms, like ``a class is a
template, and objects are copies of that template.'' This is better than
out-and-out confusion, but it still misses something important. It's an
operational definition, instead of a conceptual definition. It describes
``class'' and ``object'' in terms of the mechanical way the virtual machine
carries out its duties, rather than in terms of their role in
\textit{modeling}, which is what OOA\&D is all about.
\index{category}
In our world, every single software object will be a member of a category,
and that category will define everything about its inner structure and rules
of behavior.
\index{type}
\index{instance}
By the way, an important near-synonym for class is \textbf{type}. (It's only a
\textit{near}-synonym because primitive, non-classes like \texttt{int}s and
\texttt{boolean}s are also types.) An important exact synonym for object is
\textbf{instance}.
\index{instantiation}
\index{new@\texttt{new}}
In addition to those nouns, an important verb in our vocabulary will be the
term \textbf{instantiate}. It means ``to actually create an object of a
particular class.'' Some people use words like \textbf{construct} or
\textbf{create} for this, or even ``\texttt{new}'' (or ``\texttt{new} up'') as
a verb, but for the most part we'll stick with instantiate.
\section{A different kind of language}
\label{sec:UMLclasses}
\index{UML (Unified Modeling Language)}
\index{design}
Classes and objects are among the basic building blocks of any OO program, and
they will play a prominent role on various \textbf{UML diagrams}. UML
(``Unified Modeling Language'') is a \textit{design} language, not a
programming language. It is expressed in visual diagrams, not streams of text.
Even though it's not text-based, though, and even though there's no
``compiler'' forcing us to adhere to the syntax, it still has rules that must
be followed, and precise meanings that can be inferred.
Figure~\ref{fig:classObject} shows what a class, and an object, look like in
UML. (I'm putting classes in yellow and objects in blue, but those colors
aren't part of UML itself, just the black-and-white stuff.) Both are boxes,
but notice the class box has three compartments in it while the object box has
two.
\begin{figure}[ht]
\centering
\includegraphics[width=1.0\textwidth]{classObject.pdf} % 650x350
\caption{A class (left) and an object in UML.}
\label{fig:classObject}
\end{figure}
\subsection{Classes in UML: the first two compartments}
\index{capitalization}
Let's look at the class in detail. In the top box is its name; so far so good.
One thing to point out, though, is that in Java, \textit{the names of all
classes are \textbf{Capitalized}.} Don't ever violate this rule, for
convention's and confusion's sake!
\index{instance variable (inst var)}
\index{object-oriented}
The second compartment has the class's \textbf{instance variables}. You'll hear
people use other terms for these like like ``member variables'' and even
``class variables,'' but I strongly prefer instance variables (or ``inst vars''
for short) and here's why: \textit{every instance of a class has its own copy
of its instance variables.} This truth is absolutely fundamental to OOP, and
it's worth re-reading that sentence again and again until it's part of your
core being. As you know, declaring a plain-ol' variable like ``\texttt{int
x;}'' creates a single storage location in which a value can be stored. But
declaring an \textit{instance} variable is a far-reaching choice that destines
every \texttt{Car} (or whatever) that will come about in the future to have its
own copy of that variable. It's our way of defining the very structure of Cars
in perpetuity.
One slight headache is that the UML syntax differs from Java's a bit: instead
of listing the variable's type and then its name, we reverse them, we use
a colon instead of a space, and we omit the semicolon. Otherwise, it's pretty
straightforward to interpret that second compartment.
\index{class variable}
\index{underlined@\underline{underlined}}
\index{car@\texttt{Car}}
\index{static@\texttt{static}}
\label{mentionStatic}
By the way, one important piece of syntax in that second compartment is an
\underline{underline}. If an inst var is underlined, then it actually isn't an
``instance variable'' after all: it's a \textbf{class variable}. This means
that \textit{there's only one shared variable for the entire class, rather
than a different variable for each object.} In Figure~\ref{fig:classObject},
the integer \texttt{num} variable is the only underlined one. So even though
every \texttt{Car} has its own \texttt{make}, \texttt{model},
\texttt{odo}meter reading, \textit{etc.}, they all share one \texttt{num}
(which presumably represents the total number of \texttt{Car} objects
instantiated so far). This makes sense, since after all such a variable is not
specific to a certain \texttt{Car}. We'll see that in Java, class variables
are created by using the ``\texttt{static}'' keyword where the variable is
declared.
\subsection{Classes in UML: the third compartment}
\index{method}
\index{member function}
The third compartment isn't much harder: it contains the \textbf{methods} for
the class. Like everything it seems, programmers have multiple terms for this
too: they're called \textbf{member functions} or \textbf{class functions} on
occasion. We'll stick with \textbf{method}.
\subsubsection{Functions vs. methods}
\index{static@\texttt{static}}
\index{function!vs.~method}
\index{method!vs.~function}
\index{pass (an argument)}
\index{call (a function)}
\index{subroutine}
Many programming languages (including Python and C++) allow the programmer to
create \textbf{functions}, which are coherent chunks of code that can be
\textbf{called}, \textbf{passed} \textbf{arguments}, and \textbf{return} a
value. You've undoubtedly seen, and written, many such functions in your
previous programming courses. They're also sometimes called
``\textbf{subroutines}.''
Java is somewhat strange in this regard in that you normally don't write
ordinary functions, but rather \textbf{methods}.\footnote{As we'll see, adding
the word ``\texttt{static}'' before a method declaration makes it a so-called
``\textbf{static method},'' which \textit{is} essentially a function.}
The crucial distinction between a method and a regular ol' Joe function is
this: while you can simply call a function to trigger it, you must call a
method \textbf{\textit{on an object}}. In the example, we have a
\texttt{fillUp()} method defined on the \texttt{Car} class. Since it's not an
ordinary function, but rather an OO method, we must call it on a particular
instance of a \texttt{Car}. In Java code, this does \textit{not} work:
\label{callMethodOnObject}
\begin{verbatim}
fillUp(); // NOPE
\end{verbatim}
nor does this:
\begin{verbatim}
Car.fillUp(); // NOPE
\end{verbatim}
Instead, one must call \texttt{fillUp()} like this:
\begin{verbatim}
johnsMercedes.fillUp(); // Correct!
\end{verbatim}
\index{Mercedez-Benz}
where \texttt{johnsMercedes} is the name of a valid \texttt{Car} object,
previously instantiated. This is what we mean by ``calling \texttt{.fillUp()}
\textit{\textbf{on}} the \texttt{johnsMercedes} \texttt{Car} object.''
Beginners sometimes view this as a syntactic nuisance. It is not. It is
fundamental to what your code \textit{means}. Conceptually, it makes sense to
have a particular car, and to fill it up. It does \textit{not} make sense to
say ``hey universe, fill up cars'' (which is what ``\texttt{fillUp()}'' seems to
say) nor to say ``hey Cars-in-general, fill yourself up'' (which is what
``\texttt{Car.fillUp()}'' seems to say).
\index{capitalization}
\index{camelCase}
By the way, notice in the example I just gave, \texttt{johnsMercedes} is
\textit{not} capitalized. (The capital ``\texttt{M}'' in the middle doesn't
count; that's just an artifact of camelCase, which is a way of making multiple
words easier to read.) This is \textit{always} true: in Java, object names
should always begin with a lower-case letter.
Back to the third compartment. You can probably tell that the things inside the
parentheses are arguments to the respective methods, with the same
name-first-then-type colon-syntax, and you can probably tell that after the
closing parenthesis, you have the return type of the function. All of this
looks vaguely Java-like, and that's because even though a UML diagram is
technically programming-language-independent, language-specific things like
\texttt{int} and \texttt{String} can't help but creep in in practice. Our
thoughts betray us.
\subsubsection{Various ``special'' methods}
\label{page:instantiateConstructor}
\index{constructor}
\index{void@\texttt{void}}
A few of those methods are worthy of special note. The first one listed, called
simply ``\texttt{Car}'', is a very special kind of method called a
\textbf{constructor} which we'll be talking about a lot. Here's an iron-clad
rule which is fundamental to much that follows: \textit{whenever an object is
instantiated, one of its class's constructors is called.} This happens
automatically; it's not something we have to do ourselves. (Java's syntax for
this, as we'll see, makes it kind of look like we're calling the constructor
ourselves. This is a mixed blessing.) In Java, there are two things that
``make'' a method a constructor: (1) it must have exactly the same name as the
class, and (2) it must have \textit{no} return type. (Note that ``no'' return
type is not the same as a \texttt{void} return type! I mean \textit{no return
type at all.}\footnote{If you mistakenly include the word \texttt{void} before
your constructor when you write the code, it is officially no longer a
constructor! It's now just an ordinary method -- weirdly named the same as the
name of the class it's in -- which will \textit{not} be automatically invoked
at instantiation time as a constructor should. I once had a nasty bug at the
eleventh hour of a software release because of this exact issue.})
By the way, just as a class can have multiple methods with the same name as
long as those methods have different argument lists, so it can have multiple
constructors subject to the same conditions. This is a very common practice,
although in this first example we have only one \texttt{Car} constructor.
\index{underlined@\underline{underlined}}
\index{numCars@\texttt{numCars()}}
Also, just as in the second compartment, an \underline{underline} indicates
that the method ``goes with the whole class, not with each object.'' And just
as before, this implies the use of the \texttt{static} keyword. A
\texttt{static} method is essentially a function: \textit{i.e.}, you
\textit{don't} call it on an object. Instead, you just call it \textit{on the
class itself.} In the example above, \texttt{numCars()} method is
\texttt{static}, which means that you could write ``\texttt{Cars.numCars()}''
to retrieve the number of \texttt{Car} objects that have been instantiated to
that point. Static methods are quite rare, but they do arise occasionally, and
are always indicated with an underline in UML.
\index{getter}
\index{setter}
\index{mutator}
\index{accessor}
The other methods I'll draw your attention to are the ones that begin with
``\texttt{get}''. People call these methods ``\textbf{getters},'' and normally
they simply return the value of the instance variable in question. Often one
also has ``\texttt{set}'' methods to set the values of inst vars, although our
example doesn't have any of those. Btw, some people also call getters and
setters \textbf{accessors}, and sometimes specifically call setters
``\textbf{mutators},'' a term which always made me chuckle.
\subsection{Objects in UML}
\index{object}
\index{state}
Now let's finally examine the blue box back on p.~\pageref{fig:classObject}, which
represents an object rather than a class. It has only two compartments, not
three. That's because there's no need (in most OO languages) to say anything
about an object's methods when focusing on the object: after all, the methods
are simply defined by the class, and are common to all instances of that class.
It is important, however, to specify the current \textbf{state} of the object,
which means the values, as of now, of all its instance variables. In the
picture, you can see that there is a \texttt{Car} object in memory representing
an old Chevy Malibu with a zillion miles on it and other suboptimal features.
\index{names}
\index{Mercedez-Benz}
Perhaps the strangest thing about a UML object is the top compartment. Notice
that it says ``\texttt{:~Car}'' (``colon-Car''), which is not a typo. Here's
the sitch. The top compartment of a \textit{class} has the class's name, since
that's all there is to say about it. The top compartment of an \textit{object},
meanwhile, has the \textit{object's} name, followed by a colon and then its
class. Just like we said ``\texttt{make :~String}'' earlier, so here we can
say ``\texttt{johnsMercedes :~Car}''.
Okay...but why, then, is Figure~\ref{fig:classObject} missing the name before
the colon entirely? Because we've chosen \textit{not to name this object in the
diagram.} It's just ``a Car'' with certain properties, not a named Car. This
may seem odd, but in fact 99\% of the time we will do exactly this. And that's
because bizarrely, \textit{objects don't have names in Java}, even though it
may seem at first that they do.
More on that later. For now, just accept the fact that UML diagrams can depict
objects, and normally we don't choose to specify the object's name -- only its
type and its instance variable values.
\subsection{The value of ``design''}
\index{design}
\index{class diagram}
\index{blueprint}
Before we move on to implementation, take a step back for a moment and
consider the \textit{information} contained in that
Figure~\ref{fig:classObject}.
Suppose you were given the job to write a car maintenance tracking program, and
you were getting started figuring out how to accomplish that. I think you'll
agree that if someone handed you that diagram, it would be valuable indeed.
There's no code in it \textit{per se}, but a great deal of the work has already
been done for you! You already know what to name your class, the names and
types of all its constituent variables, and what methods its objects should
support. With the diagram alone, I'd say 70\% of the work has been done for
you.
The blueprint communicates a ton of information about decisions that have
already been made. With your structure defined, you now just need to bust out a
hammer and some nails.
\section{Classes in Java}
\index{class@\texttt{class}}
\index{java file@\texttt{.java} file}
\index{vim@\texttt{vim}}
In Java, every class is in its own file\footnote{Technically there can be
some exceptions to this, but don't worry about them now.} named the same as
the name of the class (including the capital letter) with a \texttt{.java}
extension. Operationally, we can use \texttt{vim} to create it and edit it:
\begin{verbatim}
$ vim Car.java
\end{verbatim}
\index{package declaration@\texttt{package} declaration}
\index{import statement@\texttt{import} statement}
The skeleton of any class file -- after the \texttt{package} and
\texttt{import} statements we'll talk about later (p.~\pageref{sec:packages}
and p.~\pageref{sec:import}, respectively) -- is the class definition, with
curly braces:
\begin{Verbatim}[samepage=true,fontsize=\footnotesize,frame=single]
class Car {
}
\end{Verbatim}
\index{public@\texttt{public}}
You may be used to putting the word ``\texttt{public}'' before the word
\texttt{class} here. For now, we won't do this, and I'll encourage you to
ditch the habit of making classes \texttt{public} by knee-jerk reaction. As
we'll learn, you want to lean towards making things ``as private as possible''
until you have reason to do otherwise.
\subsection{Instance variables in Java}
\index{instance variable (inst var)}
Instance variables go directly inside the class definition, and outside of any
method:
\begin{Verbatim}[samepage=true,fontsize=\footnotesize,frame=single]
class Car {
String make, model;
int yearsOld;
int odo;
double galsRemaining;
double sizeOfTank;
double gasMileage;
}
\end{Verbatim}
\index{private@\texttt{private}}
You may be used to seeing the word ``\texttt{private}'' before each instance
variable, and I do applaud that practice. More on that later. For now, we'll
leave it off just because it's not necessary to compile. Realize that it's not
the word \texttt{private} that makes something an instance variable; rather,
it's the fact that it's defined directly inside the class, rather than within
a method.
\subsection{Constructors in Java}
\index{constructor}
Next on the diagram is our constructor. We put in the boilerplate to get us
started:
\begin{Verbatim}[samepage=true,fontsize=\footnotesize,frame=single]
class Car {
...
Car(String make, String model) {
}
}
\end{Verbatim}
and now for the first time we have to actually think.
A constructor, as I said, is automatically called whenever an object comes
into existence. This is our ``hook'' to set up the object for success when
methods are called on it later. Think of it this way: your constructor is
called whenever a new object is about to come off the assembly line and enter
the real world. Your job in the constructor is to do everything necessary to
make sure it's ready for prime time.
Often this will involve initializing the instance variables to reasonable
values. Sometimes it will include other things, like registering its existence
in some global repository of objects, or initializing a connection to a
network, or writing itself to a database. The key question to ask yourself is,
``what do I need to do to ensure this object is `legit' and doesn't break
anything when it's being used?''
\subsection{Analyze \texttt{this}}
\index{this@\texttt{this}}
In our case, initializing the instance variables are all we need to do in the
constructor. First, let's set the object's \texttt{make} and \texttt{model} to
what was passed:
\begin{Verbatim}[samepage=true,fontsize=\footnotesize,frame=single]
class Car {
...
Car(String make, String model) {
this.make = make;
this.model = model;
}
}
\end{Verbatim}
\normalsize
\index{Gosling, James}
If this is the first time you've seen the odd word ``\texttt{this}'' in a
program, have a good chuckle. What a weird word choice! But Gosling \&
Co.~chose this word to denote a central OO programming concept. The word
``\texttt{this}'' means one of two different things, and they both need to be
memorized:
\begin{samepage}
\definecolor{shadecolor}{rgb}{.9,.9,1}
\begin{shaded}
\begin{compactenum}
\item Inside a \textit{constructor}, ``\texttt{this}'' means ``the object that is
currently being instantiated.''
\item Inside a \textit{method}, ``\texttt{this}'' means ``the object the
method was called on.''
\item[$\times$.] (Anywhere else, ``\texttt{this}'' is illegal.)
\normalsize
\end{compactenum}
\end{shaded}
\end{samepage}
It's weird and meta and self-referential, but it's also necessary. We need to
to have a name for ``the very object I'm `in' right now,'' and
``\texttt{this}'' is our (awkward) name to refer to that.
So in our constructor, when we say ``\texttt{this.make}'' we mean ``the
\texttt{make} instance variable of this very object that is in the process of
being birthed.'' We set that to the \texttt{make} argument that was passed to
the constructor. Ditto with \texttt{model}. Note: oftentimes (namely, when it's
unambiguous), using \texttt{this} is optional. But \textbf{in this book I'm
\textit{always} going to use \texttt{this} before instance variables, to drill
home the point that they are very different from ordinary, local variables.}
Just be aware that you'll see code out in the wild where lazy programmers don't
always use \texttt{this} for inst vars, and you'll be fine.
\index{initialization}
Now for our other inst vars. Some of them make sense to be set to zero:
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
class Car {
...
Car(String make, String model) {
this.make = make;
this.model = model;
this.yearsOld = 0;
this.odo = 0;
this.galsRemaining = 0.0;
}
}
\end{Verbatim}
since brand new cars are in fact zero years old, have a 000000 odometer, and
have no gas in their tank (maybe). Zero values for the other two don't make
sense, however; brand new cars still have a gas tank of a certain size, and
they certainly get more than 0 mpg. For this example, I'm going to go with a
very limited notion of automotive properties:
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
class Car {
...
Car(String make, String model) {
this.make = make;
this.model = model;
this.yearsOld = 0;
this.odo = 0;
this.galsRemaining = 0.0;
if (make.equals("Chevy") || make.equals("GM")) {
this.sizeOfTank = 21;
} else {
this.sizeOfTank = 13;
}
if (make.equals("Chevy") && model.equals("Malibu")) {
this.gasMileage = 3;
} else {
this.gasMileage = 24;
}
}
}
\end{Verbatim}
I'm totally not bitter about my car's gas mileage, by the way.
\subsection{Methods in Java}
The other methods follow a similar syntactic pattern. But it's super important
to keep this truth in the front of your mind: \textit{because they are methods
(not functions), they are called \textbf{on an object.}} That means that
you can refer to instance variables inside of them -- and when you do, you're
talking about \textit{the instance variables of the object the method was
called on.} Put another way, you're talking about the instance variables of
\texttt{this}.
\subsubsection{``Client code'' and thinking reactively}
When you write methods in an OO program, you have to think reactively, not
proactively. What I mean is this. When you write a procedural, old school
program, you're the one in control. You set the agenda. In your
\texttt{main()} you say, ``first do this, then do that; create these three
variables, perform a computation, and then print the result.''
We all learned how to program this way. But in OO, you kind of have to think
backwards from that. Writing a method isn't like calling it; instead of giving
orders, you're providing a service to whoever called you. So when you write a
method, you have to think, ``okay, some other part of the code is now calling
me, for reasons of its own. What do I do in response to that?''
\index{client code}
Our term for ``that other part of the code that is now calling me'' is
\textbf{client code} (or sometimes just ``a \textbf{client}.'') The word
``client'' is used in a lot of different ways in high-tech, but here we just
mean ``the code that wants to use a particular object.'' The word connotes a
respected customer, whom we want to treat well.
Very well, some client code calls one of our methods. How should we react?
\index{state}
Often we'll react by updating the object's \textbf{state} to reflect what
should happen to it as a result of the method being called. Sometimes we'll
produce (return) a value that is stored by the object in question or
computed on the fly. Other times we'll trigger some side effect, like printing
to the screen, writing to a database, or calling some \textit{other} method(s)
on the same or a different object.
\index{implement@``to implement'' (to code)}
\index{fillUp@\texttt{.fillUp()}}
This is best seen through examples. Let's implement\footnote{The verb
\textbf{to implement} means ``to take a design and actually build it out.'' It
is a synonym for the verb \textbf{to code}.} the \texttt{.fillUp()} method
first. Don't think about Java; think about cars. If I fill up a car, what
happens?
Does the make or model or mileage change? Of course not. The amount of gas in
the tank does. And ``fill 'er up'' means to raise it to its maximum. The
correct implementation of \texttt{.fillUp()}, then, is simply:
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
class Car {
...
void fillUp() {
this.galsRemaining = this.sizeOfTank;
}
}
\end{Verbatim}
At the risk of repetition, note the word \texttt{this} before each of these
variable names, indicating in each case that we mean ``the inst var in this
object by that name.''
\medskip
In the same vein, we ask ourselves, ``suppose some client code asks me what
percentage full my tank is. What answer do I give?'' The proper response
involves these same two inst vars and a little math:
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
class Car {
...
double getTankPerc() {
return this.galsRemaining / this.sizeOfTank * 100;
}
}
\end{Verbatim}
\vspace{-.15in}
\index{getter}
\index{setter}
Some methods, like accessors, are no-brainers. Here's a getter:
\vspace{-.15in}
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
class Car {
...
String getModel() {
return this.model;
}
}
\end{Verbatim}
\vspace{-.15in}
If a client asks me what my model is, I just tell them my model, duh. A setter
generally looks like this:
\vspace{-.15in}
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
class Car {
...
void setMake(String make) {
this.make = make;
}
}
\end{Verbatim}
\medskip
\pagebreak
\index{drive@\texttt{.drive()}}
Finally, what if a client instructs me to drive $n$ miles? How should my
internal state be adjusted to reflect that?
This is the most difficult one, and again it requires you to think about cars
rather than about Java. Mentally run through the variables we've chosen to
represent a car, and ask yourself which ones need to change, and how? You'll
realize that the odometer and the gas tank level are the two we need to
modify. When someone drives a car $n$ miles, the odometer needs to increase by
$n$ miles (else it ain't legal); also, the gas tank needs to be reduced by
$\frac{n}{m}$ gallons, where $m$ is the car's gas mileage in mpg. So here we
go:
\begin{Verbatim}[samepage=true,fontsize=\footnotesize,frame=single]
class Car {
...
void drive(int numMiles) {
double galsBurned = numMiles / this.gasMileage;
this.galsRemaining -= galsBurned;
this.odo += numMiles;
}
}
\end{Verbatim}
(Recall that the ``\texttt{-=}'' operator in Java means ``subtract the thing on
the right-hand side permanently from the thing on the left-hand side''; in other
words, ``\texttt{x -= y;}'' is a shorthand for, and exactly the same thing as,
``\texttt{x = x - y;}'')
Now note that some of these variables have \texttt{this} before them, and others
don't, which distinguishes which are semi-permanent parts of the object, and
which are merely parameters names and local variables that this method made up.
Double-check me: if you look back at page~\pageref{fig:classObject}, you're not
going to see any inst vars called ``\texttt{numMiles}'', or
``\texttt{galsBurned}''. Those were created in the spur of the moment, just
for this method.
\subsubsection{``Static methods'' and ``static inst vars''}
\index{class variable}
Now as I mentioned on p.~\pageref{mentionStatic}, some ``instance variables''
are actually not \textit{instance} variables at all, but rather class
variables. For a class variable, all objects of that class (in the present
example, all \texttt{Car} objects) would share the \textit{same} value for the
variable, rather than each object getting its own copy. This is rare, but it
does happen.
\index{function!vs.~method}
\index{method!vs.~function}
Also, recall that in unusual cases a ``method'' might not be a method at all,
but just a regular function that takes arguments and returns a value. With such
a function you don't call it \textbf{\textit{on}} a particular object, but
rather ``just call it.'' Again, this is the exception, not the norm.
\index{static@\texttt{static}}
These situations are similar in that both of them seek to associate something
(a variable or a subroutine) with \textit{the class as a whole}, rather than
with individual instances. And that's why the syntax for them is the same. In
both cases, the way to make them happen in Java is the \texttt{static} keyword.
\smallskip
It's actually hard to think of good examples of class variables (sometimes
called ``static instance variables,'' an oxymoron that drives me nuts). But
I'll try. Suppose we want to keep track of the \textit{number} of \texttt{Car}s
that have been created. This is an integer, of course, but importantly we don't
want to make it an instance variable, since it's a property of ``cars in
general,'' not any particular car.
Additionally, we need to be able to access it, and so we'll use a ``static
method'' (a.k.a.~a regular function, defined on the class) that will retrieve
its value. Putting it all together, we get:
\vspace{.15in}
\begin{Verbatim}[fontsize=\footnotesize,samepage=true,frame=single,framesep=3mm]
class Car {
...
static int numCars;
...
Car(String make, String model) {
...the rest of the constructor...
Car.numCars++;
}
...
static int getNumCars() {
return Car.numCars;
}
}
\end{Verbatim}
By marking \texttt{numCars} static, we ensure that unlike \texttt{make},
\texttt{model}, and the rest, there's only one \texttt{numCars} variable no
matter how many \texttt{Car}s we instantiate. Note that the way to call the
\texttt{getNumCars()} function is like this:
\begin{verbatim}
int n = Car.getNumCars(); // Correct!
\end{verbatim}
\textit{not} like this:
\begin{verbatim}
int n = johnsMercedes.getNumCars(); // NOPE
\end{verbatim}
\index{Mercedez-Benz}
This is the exact opposite of the situation on p.~\pageref{callMethodOnObject},
and it makes sense because we aren't asking a specific car (like John's
Mercedes-Benz) how many cars exist. We're just asking the universe that
question. So to refer to a static variable, instead of \texttt{this} before the
dot, we put the name of the class before the dot.
\smallskip
Also notice that we incremented \texttt{numCars} in our class constructor. This
is so that as soon as each \texttt{Car} comes off the assembly line (no pun
intended), we'll automatically click the turnstile and count it towards our
total.
\section{Objects in Java}
\index{object}
We've now coded a class from the ground up (the complete code listing is in
Figure~\ref{fig:carClassCodePreExceptions}.) We did this so clients can
instantiate objects of that type and do something with them. Let's make a
simple \texttt{main()} method to do just that.
You'd be surprised how many beginning programmers try to drive 23 miles like
this:
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
public static void main(String args[]) {
drive(23); // WRONG!
}
\end{Verbatim}
or this:
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
public static void main(String args[]) {
Car.drive(23); // equally WRONG!
}
\end{Verbatim}
\index{object-oriented}
Yes you'll get compiler errors, but those errors reflect a deeper and more
fundamental misunderstanding. In OOP, you have to call a method \textit{on an
object}. Conceptually, nothing else makes sense. In real life you don't
``drive in general,'' and you don't ask ``automobiles in general'' to drive
you places. Instead, you have to drive \textit{a particular car} somewhere.
Here's how:
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
public static void main(String args[]) {
Car minivan = new Car("Toyota","Sienna");
minivan.drive(23); // correct!
}
\end{Verbatim}
\index{new@\texttt{new}}
\index{instantiation}
The keyword ``\texttt{new}'' is utterly crucial here. In Java, \textit{the only
way to instantiate an object is to use \texttt{new}}. It causes a fresh object
of the appropriate type to spring into existence, complete with memory to hold
its instance variables. And the appropriate constructor is called, of course,
to set that object up for prime time.
We got errors before because we didn't even \textit{have} a car to do anything
with. There was no memory set aside, no constructor called to set up the
object, nothing. We tried a shortcut, and that was madness. But now that we
know how to instantiate objects, we can do so to several and create a whole
new world, as in Figure~\ref{fig:wholeNewWorld} on
p.~\pageref{fig:wholeNewWorld}. All the code in that figure is legit, and
shows that our \texttt{Car} class has uses.
\begin{figure}[h]
\centering
\begin{Verbatim}[samepage=true,fontsize=\footnotesize,frame=single]
public static void main(String args[]) {
// The archaic Davies family vehicles
Car famCar = new Car("Honda","CR-V");
famCar.setYear(2008);
Car stephensLemon = new Car("Chevy","Malibu");
famCar.setYear(2001);
// Grammy lives in Colorado
Car grammysCar = new Car("Lexus","ES");
grammysCar.setYear(2025);
// Caravan to Disneyworld! (Grammy's meeting us there.)
famCar.fillUp();
famCar.drive(500);
stephensLemon.fillUp();
stephensLemon.drive(500);
System.out.println("The Honda is " + famCar.getTankPerc() +
"% full, while the Chevy is " +
stephensLemon.getTankPerc() + "% full.");
grammysCar.drive(1899); // a long way from Colorado
}
\end{Verbatim}
\caption{A client \texttt{main()} program that uses the \texttt{Car} class.}
\label{fig:wholeNewWorld}
\end{figure}
\subsection{Printing an object}
One last thing before we bring this chapter to a close. Suppose we're
debugging our program, and we want to print out the values of various
variables to help us hunt down an error. Printing an \texttt{int} or other
standard type is straightforward:
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
int numEnchiladas = 3;
System.out.println("We'll eat " + numEnchiladas + " enchiladas.");
\end{Verbatim}
and will produce a message like ``\texttt{We'll eat 3 enchiladas.}'' What
happens, though, if we print out an \textit{object}, like a \texttt{Car}? How
can such a complex entity be reduced to a string of text?
Heck, let's try it:
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
Car porsche = new Car("Porsche","Carrera");
porsche.setYearsOld(2);
System.out.println("My car is " + porsche + ".");
\end{Verbatim}
The output we get is:
\begin{verbatim}
My car is Car@4aa298b7.
\end{verbatim}
Whoa. The word ``\texttt{Car}'' is perhaps not surprising, but what's the rest
of that gunk?
\index{memory address}
It turns out that Java's default way of rendering an object as a
\texttt{String} is to concatenate the name of the class, an ``at'' sign,
followed by \textit{the memory address} in which it is stored. We'll talk much
more about memory in the next chapter. For now, just think of the memory
address as a unique number\footnote{Yes, it is indeed a number, despite the
fact that it has letters in it like '\texttt{a}' and '\texttt{b}'. It's
printed here in \textbf{hexadecimal}, which is a base-16 number system instead
of the base-10 system non-computer-science humans use.} that identifies the
object, like an SSN.
\begin{samepage}
\label{pg:toString}
\index{override}
\index{toString@\texttt{.toString()}}
The cool thing is, we can \textbf{override} this functionality at will, and
change the way \texttt{Car}s will be printed. Check it out. Create a method in
the \texttt{Car} class called \texttt{.toString()}. It must:
\begin{compactenum}
\itemsep.1em
\item be called exactly ``\texttt{.toString()}''.
\item take no argument.
\item return a \texttt{String}.
\index{public@\texttt{public}}
\item have the word \texttt{public} immediately before the return type. (We'll
talk a lot about what \texttt{public} means in future chapters. For now, it just has to
be there.)
\end{compactenum}
\end{samepage}
Here's one:
\begin{Verbatim}[samepage=true,fontsize=\scriptsize,frame=single]
public String toString() {
return "a " + this.yearsOld + "-yr-old " + this.make + " " + this.model;
}
\end{Verbatim}
We're assembling various aspects of the vehicle into a sensible, readable
string. Now, when we run \textit{the same code} as above, our output is this:
\begin{verbatim}
My car is a 2-yr-old Porsche Carrera.
\end{verbatim}
Notice that we didn't explicitly ever call \texttt{.toString()}! Instead, we
just used a \texttt{Car} object in a context in which a \texttt{String} was
required, and Java faithfully called our method instead of the one that
generated the memory address. Pretty cool.
\index{inheritance}
This is actually our first foray into a really deep and powerful technique
called ``inheritance,'' about which much more will come in later chapters. For
now, just grasp the idea that Java lets us override its general behavior for
specific kinds of objects, which gives us tremendous power and flexibility.
% TODO: change yearsOld to yearManufactured, and make encapsulation point.
\begin{figure}
\begin{Verbatim}[fontsize=\scriptsize,frame=single]
class Car {
String make, model;
int yearsOld, odo;
double galsRemaining, sizeOfTank, gasMileage;
static int numCars;
Car(String make, String model) {
this.make = make;
this.model = model;
this.yearsOld = 0;
this.odo = 0;
this.galsRemaining = 0;
if (make.equals("Chevy") || make.equals("GM")) {
this.sizeOfTank = 21;
} else {
this.sizeOfTank = 13;
}
if (make.equals("Chevy") && model.equals("Malibu")) {
this.gasMileage = 3;
} else {
this.gasMileage = 24;
}
Car.numCars++;
}
public String toString() {
return "a " + this.yearsOld + "-yr-old " + this.make + " " + model;
}
String getMake() { return this.make; }
String getModel() { return this.model; }
int getYearsOld() { return this.yearsOld; }
void setYearsOld(int x) { this.yearsOld = x; }
static int getNumCars() { return Car.numCars; }
void fillUp() {
this.galsRemaining = this.sizeOfTank;
}
double getTankPerc() {
double perc = this.galsRemaining / this.sizeOfTank * 100;
return perc;
}
void drive(int numMiles) {
double galsBurned = this.numMiles / this.gasMileage;
this.galsRemaining -= galsBurned;
this.odo += this.numMiles;
}
}
\end{Verbatim}
\caption{A complete Java implementation of the \texttt{Car} class.}
\label{fig:carClassCodePreExceptions}
\end{figure}