-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinheritance2.tex
More file actions
910 lines (775 loc) · 36.9 KB
/
inheritance2.tex
File metadata and controls
910 lines (775 loc) · 36.9 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
% TODO: refer to "special kinds of exceptions" from ch.5.
\chapter{Inheritance (2 of 2)}
\label{ch:inheritance2}
\index{inheritance}
I split what was once a long inheritance chapter into two. So you're probably
back from a snack break, a nap, or a game of Ultimate. Let's get warmed up
again.
\index{zoo}
A class diagram for a ``Zoo'' program is in Figure~\ref{fig:zooClass}. Study
the code on the following page (Figure~\ref{fig:zooCode}) and predict its
output.
\begin{figure}[ht]
\label{zooExample}
\centering
\includegraphics[width=0.9\textwidth]{zooClass.pdf}
\caption{A class diagram for the Zoo program.}
\label{fig:zooClass}
\end{figure}
\index{animal@\texttt{Animal}}
\index{cow@\texttt{Cow}}
\index{duck@\texttt{Duck}}
\index{bear@\texttt{Bear}}
\index{bird@\texttt{Bird}}
\index{move@\texttt{.move()}}
\index{makeNoise@\texttt{.makeNoise()}}
We have an \texttt{Animal} class with a number of subclasses, and one of them
even has its \textit{own} subclass. In each case, we override one, both, or
neither of the base class's methods.
\begin{figure}
\begin{Verbatim}[fontsize=\scriptsize,samepage=true,frame=single]
class Animal { class Bird extends Animal {
public void makeNoise() { public void makeNoise() {
System.out.println("Growl!"); System.out.println("Chirp");
} }
public void move(int dist) { public void move(int dist) {
for (int i=0; i<dist; i++) { System.out.println("Flap");
System.out.print("tramp "); }
} }
System.out.println();
}
} class Duck extends Bird {
public void makeNoise() {
System.out.println("Quack");
class Cow extends Animal { }
public void makeNoise() { }
System.out.println("Mooooo");
}
} class Bear extends Animal { }
class Zoo {
public static void main(String args[]) {
ArrayList<Animal> zoo = new ArrayList<Animal>();
zoo.add(new Animal());
zoo.add(new Bird());
zoo.add(new Cow());
zoo.add(new Bear());
zoo.add(new Duck());
generateCacophony(zoo);
}
private static void generateCacophony(ArrayList<Animal> animals) {
for (Animal a: animals) {
a.makeNoise();
a.move(3);
System.out.println();
}
}
}\end{Verbatim}
\caption{The Zoo program.}
\label{fig:zooCode}
\end{figure}
\begin{samepage}
The output of the program, as you can easily verify, is:
\begin{Verbatim}[fontsize=\footnotesize,samepage=true,frame=single]
Growl!
tramp tramp tramp
Chirp
Flap
Mooooo
tramp tramp tramp
Growl!
tramp tramp tramp
Quack
Flap
\end{Verbatim}
\end{samepage}
\index{inheritance!top-down (interface)}
Lots of top-down inheritance here. Notice that the \texttt{Bear} class is
completely unchanged from its superclass: evidently, the generic animal
behavior works fine for bears, at least as far as moving and making noise
goes. This is not an error.
You also may have noticed that the \texttt{Bird}'s \texttt{.move()} method
completely ignores its \texttt{distance} argument. That, too, is not a
problem.
\index{tree}
\index{inheritance hierarchy}
Finally, and most importantly, note that the \texttt{Duck} class does not
override \texttt{.move()}, but its superclass (\texttt{Bird}) does, and so a
\texttt{Duck} will ``\texttt{Flap}'' like ordinary \texttt{Bird}s
do. The rule is: when a method is called on an object, the code in its class
is called, unless the class doesn't define that method. In that case, Java
looks for the method in its immediate superclass, then its superclass's
superclass, \textit{etc.}~all the way up the inheritance hierarchy, calling
the first one it finds. This makes sense: since a \texttt{Duck} \textbf{is-a}
\texttt{Bird}, it is sensible to make it move like a \texttt{Bird} rather than
like a generic \texttt{Animal}.
\section{Polymorphism}
\index{polymorphism}
This technique goes by a funny name, by the way: \textbf{polymorphism}. It's
one of those geeky-sounding words useful for slinging at parties when you want
an annoying person to move away from you.
\index{transparent}
I define polymorphism (specifically, ``subtype polymorphism,'' which is what
we're dealing with here) as \textit{transparently treating objects differently
based on their type.} The word ``transparently'' means ``without the
programmer having to worry about it.''
Essentially, polymorphism is another way to think about top-down inheritance.
We have a generic set of operations (like ``move'' and ``make noise''), each
of which can be personalized in custom ways by specific subclasses, but which
clients can simply call at the desired times without having to be aware of
those subclasses. ``The right thing'' simply happens based on the object's
type, without the programmer having to resort to a giant chain of if/else
statements or some other monstrosity. This is because the language itself
automatically dispatches the method call to the correct code.
In terms of the concrete zoo example, polymorphism basically says: ``the way
you direct any animal to make noise is the same: telling a duck to make noise
uses the exact same code as telling a cow to make noise. Yet different things
happen in each case, because of how Java enables the subtype-customization to
take place."
\subsection{\texttt{instanceof} is evil}
\index{instanceof operator (evil)@\texttt{instanceof} operator (evil)}
It may help you understand this if I contrast it with a \textit{non}-example
of polymorphism.
\index{Pok\'{e}mon}
\index{hyperbeam}
\index{thunder shock}
\index{attack@\texttt{.attack()}}
Suppose we have a \texttt{Pokemon} class, instances of which represent various
fictional fighting critters and their moves and stats. We also have a
\texttt{Power} class used to represent a particular superpower like ``thunder
shock'' or ``hyperbeam.'' Each special type of power will be its own subclass
of \texttt{Power}, in true object-oriented inheritance style. And for this
simple example, we'll say that each \texttt{Pokemon} has just one ``primary
power'' that it can use in combat. Whenever a \texttt{Pokemon} object's
\texttt{.attack()} method is called, it will use its primary power on the foe
it is passed.
\index{modularity}
Figure~\ref{fig:wrongPokemon} shows the \textbf{WRONG} way to code this. The
\texttt{.attack()} method itself, in the \texttt{Pokemon} class, is
scrutinizing its \texttt{primaryPower} object, figuring out what subclass it
is and responding appropriately. You can see the (evil) Java
\texttt{instanceof} operator in use here. It is a way of determining at
run-time whether or not an object is of a particular class. \textbf{Using
\texttt{instanceof} is almost always bad programming practice} since it
violates encapsulation, reduces modularity, and eschews polymorphism.
Among other things, this design creates a gigantic (and ever-growing, as more
powers are added to the program) \texttt{if}/\texttt{else} chain to do the
work that Java already does automatically. And that huge type-checking
mechanism, besides being unwieldy and error-prone, is plopped right inside the
\texttt{Pokemon} class, which is not the right place for it. (That code
concerns various types of \textit{powers}, not \textit{Pok\'{e}mon}.)
\begin{figure}[ht]
\begin{Verbatim}[fontsize=\small,samepage=true,frame=single]
public class Pokemon {
private Power primaryPower;
public void attack(Pokemon foe) {
if (this.primaryPower instanceof Thundershock) {
// do the "thundershock" stuff to the foe
}
else if (this.primaryPower instanceof RoarOfTime) {
// do the "roar of time" stuff to the foe
}
else if ...
}
}
public class Power {
...
}
public class Thundershock extends Power {
...
}
public class RoarOfTime extends Power {
...
}
\end{Verbatim}
\caption{The {\color{red} \underline{\textbf{WRONG}}} way to implement
Pok\'{e}mon powers, using the \texttt{instanceof} operator.}
\label{fig:wrongPokemon}
\end{figure}
\index{roar of time}
\index{useAgainst@\texttt{.useAgainst()}}
Figure~\ref{fig:rightPokemon}, on the other hand, shows a good, healthy,
proper OO design for the Pok\'{e}mon model. None of that
\texttt{if}/\texttt{else} junk is even necessary, and the \texttt{Pokemon}'s
\texttt{.attack()} method becomes a one-liner, as it should be. Java will
automatically call the proper ``thunder shock'' code, ``roar of time'' code,
``hyperbeam'' code, or whatever, without us having to try to do its work for
it. And adding a new \texttt{Power} is just a matter of creating a new,
encapsulated subclass, with its own \texttt{.useAgainst()} code. Neither the
\texttt{Power} superclass nor the \texttt{Pokemon} class need be disturbed by
this addition. It all works seamlessly.
\definecolor{darkgreen}{rgb}{0,.65,0}
\begin{figure}[ht]
\begin{Verbatim}[fontsize=\small,samepage=true,frame=single]
public class Pokemon {
private Power primaryPower;
public void attack(Pokemon foe) {
this.primaryPower.useAgainst(foe);
}
}
public class Power {
public void useAgainst(Pokemon foe) {
// use the basic, default power on the foe
}
}
public class Thundershock extends Power {
public void useAgainst(Pokemon foe) {
// do the "thundershock" stuff to the foe
}
}
public class RoarOfTime extends Power {
public void useAgainst(Pokemon foe) {
// do the "roar of time" stuff to the foe
}
}
\end{Verbatim}
\caption{The {\color{darkgreen} \underline{\textbf{right}}} way to implement
Pok\'{e}mon powers, using subtype polymorphism.}
\label{fig:rightPokemon}
\end{figure}
\section{Getting abstract}
\subsection{Abstract methods}
\index{zoo}
\index{animal@\texttt{Animal}}
\index{cow@\texttt{Cow}}
\index{duck@\texttt{Duck}}
\index{bear@\texttt{Bear}}
\index{bird@\texttt{Bird}}
\index{move@\texttt{.move()}}
\index{makeNoise@\texttt{.makeNoise()}}
Okay, back to the Zoo example from p.~\pageref{zooExample}. For each type of
animal, it was up to the subclass to decide whether to override a method or
not. If the subclass was happy with the base class's behavior (like
\texttt{Cow} was with \texttt{.move()}, or \texttt{Bear} was with everything)
it could just ignore that method and default to ordinary animal behavior.
\index{getNumChromosomes@\texttt{.getNumChromosomes()}}
\index{chromosome}
What if we had a method, though, where there was no reasonable default
behavior to define? Let's add a method \texttt{.getNumChromosomes()} which
will return the number of DNA molecules in that species. Unlike making noise,
which we might plausibly say is ``growling, unless further specified for a
particular animal,'' perhaps there isn't any ``default number of chromosomes''
that makes sense.\footnote{Consider: a fruit fly has only 8 chromosomes, while
a tasmanian devil has 14, a human has 46, a potato 48, a silkworm 56, and a
catfish 104. Given these examples, what default value would have any merit?}
Note that we still want to be able to call \texttt{.getNumChromosomes()} on
\textit{any} \texttt{Animal}, no matter what type. So it's no good to just
leave the method out of the \texttt{Animal} class and only define it on
subclasses.
\index{abstract method}
The solution to our dilemma is to make \texttt{.getNumChromosomes()} an
\textbf{abstract method}. ``Abstract'' means that even though it's defined in a
superclass -- with a name, parameter list, and return type -- there's not
actually any \textit{code} for it there! Here's what it looks like:
\begin{Verbatim}[fontsize=\small,samepage=true,frame=single]
class Animal { // (not finished yet...)
abstract public int getNumChromosomes();
...
}
\end{Verbatim}
It looks a little strange, with a semicolon prematurely truncating the method
signature. But by doing this, we're declaring that even though there's no
method \textit{body} for \texttt{.getNumChromosomes()} in the \texttt{Animal}
class, we still want to be able to call it on an \texttt{Animal}. Individual
subclasses provide their own implementation; for example:
\begin{Verbatim}[fontsize=\small,samepage=true,frame=single]
class Cow extends Animal {
public int getNumChromosomes() {
return 60;
}
...
}
\end{Verbatim}
Notice that the subclasses do \textit{not} include the keyword \texttt{abstract}
on the method.
\vspace{.7in}
\subsection{Abstract classes}
Now I know what you're thinking. ``This is all fine, but what if we have a
plain-old-\texttt{Animal} object and call \texttt{.getNumChromosomes()} on
it?''
\begin{Verbatim}[fontsize=\small,samepage=true,frame=single]
Cow c = new Cow();
int numc = c.getNumChromosomes(); <-- returns 60
Animal a = new Animal();
int numa = a.getNumChromosomes(); <-- ???
\end{Verbatim}
There's no code to run for a generic \texttt{Animal}, so what value would we
get back?
\index{instantiation}
This is indeed a dilemma, and Java solves it in the only sensible way: it says
\textit{you can't make a plain-old-\texttt{Animal} anymore.} The rule is: if
any method of a class is abstract, \textbf{the class itself must be abstract},
which means it is \textit{un-instantiatable.} In other words, the Java
compiler forces us to amend our \texttt{Animal} class as follows:
\begin{Verbatim}[fontsize=\small,samepage=true,frame=single]
abstract class Animal {
public void makeNoise() {
System.out.println("Growl!");
}
public void move(int distance) {
for (int i=0; i<distance; i++) {
System.out.print("tramp ");
}
System.out.println();
}
abstract public int getNumChromosomes();
}
\end{Verbatim}
If we ever try to write the code ``\texttt{new Animal()}'', Java will (rightly)
stop us with a compilation error.
\begin{Verbatim}[fontsize=\footnotesize,samepage=true]
Animal.java:5: error: Animal is abstract; cannot be instantiated
new Animal();
^
1 error
\end{Verbatim}
\begin{samepage} Note that every instantiatable subclass needs to be
non-\texttt{abstract}, and therefore \textit{it must have a body for every one
of its methods}, defined in either itself or in one of its superclasses. For
example, as soon as we add the \texttt{abstract}
\texttt{.getNumChromosomes()}, our \texttt{Cow.java} suddenly won't compile
either:
\begin{Verbatim}[fontsize=\footnotesize,samepage=true]
Cow.java:4: error: Cow is not abstract and does not override abstract
method getNumChromosomes() in Animal
class Cow extends Animal {}
^
1 error
\end{Verbatim}
\normalsize
\end{samepage}
So we'll need to define \texttt{.getNumChromosomes()} in \texttt{Cow} and
\texttt{Bear} (or else make them \texttt{abstract}). What about \texttt{Duck}
and \texttt{Bird}? It depends on which of these classes (if either) we want to
be \texttt{abstract}. If we want to be able to ``\texttt{new Bird()}'' and also
``\texttt{new Duck()}'', then at \textit{least} \texttt{Bird} will have to
provide a \texttt{.getNumChromosomes()} method. (And \texttt{Duck}'s would be
optional. If in fact \texttt{Duck}s have a different number of chromosomes
than ordinary \texttt{Bird}s, we'd want to also make one on the \texttt{Duck}
class.) If, on the other hand, we're happy for \texttt{Bird} to be abstract
(and thus un-instantiatable), we could choose to define it \textit{only} on
\texttt{Duck} and call it a day. It all depends on what makes sense for the
domain.
Putting all this abstract stuff together, here are the rules:
\begin{enumerate}
\itemsep.1em
\item A class cannot be instantiated if it's declared \texttt{abstract}. (Only
its subclasses possibly can be.)
\item If there is any \texttt{abstract} method on a class, the class itself
must be declared \texttt{abstract}.
\item If a class \texttt{A} inherits from some other class \texttt{B}, and
\texttt{B} has abstract method(s) on it, \texttt{A} must provide
implementation(s) for all of those methods, or else \texttt{A} be declared
\texttt{abstract} as well.
\end{enumerate}
\subsection{UML notation}
\index{abstract method}
\index{abstract class}
\index{stereotype}
There are two different ways to mark a method or class as \texttt{abstract} in
UML. One is to put the name of the method or class in italics. That works well
if you're using a design tool like ArgoUML or Rationale Rose to create your
diagrams. Otherwise, if you're doing it by hand, you add a
(``$\ll$abstract$\gg$'') stereotype. I've shown both approaches in
Figure~\ref{fig:zooClassAbstract}.
\begin{figure}
\centering
\includegraphics[width=0.9\textwidth]{zooClassAbstract.pdf}
\caption{Using \textit{italics}, and the $\ll$abstract$\gg$ stereotype, to
indicate abstract classes and methods.}
\label{fig:zooClassAbstract}
\end{figure}
\section{That's just super}
\index{super@\texttt{super}}
\subsubsection{Calling a superclass's methods with ``\texttt{super.}''}
Occasionally, it will make sense for a method in a class to explicitly call a
method in its superclass. For instance, suppose we said, ``When asked to make
noise, a \texttt{Duck} should `\texttt{Quack}' but then \textit{also} do
whatever ordinary \texttt{Bird}s usually do.'' We would write that as follows:
\begin{Verbatim}[fontsize=\footnotesize,samepage=true,frame=single]
class Duck extends Bird {
public void makeNoise() {
System.out.println("Quack");
super.makeNoise();
}
}
\end{Verbatim}
The ``\texttt{super.}'' prefix (pronounced ``super dot'') says to call the
version of \texttt{.makeNoise()} that's defined in the \texttt{Bird}
class, not the \texttt{Duck} one. (And a good thing, too: otherwise we'd have
an infinite loop with \texttt{.makeNoise()} repeatedly calling itself!)
Written this way, a \texttt{Duck} will make this noise:
\vspace{-.15in}
\begin{Verbatim}[fontsize=\small,samepage=true,frame=none]
Quack
Chirp
\end{Verbatim}
\vspace{-.15in}
\index{chipmunk@\texttt{Chipmunk}}
As another example, we might define a class \texttt{Chipmunk} that moves twice
as rapidly as normal animals. If we defined its \texttt{.move()} method thus:
\begin{Verbatim}[fontsize=\footnotesize,samepage=true,frame=single]
class Chipmunk extends Animal {
public void move(int distance) {
int doubleDist = distance * 2;
super.move(doubleDist);
}
}
\end{Verbatim}
then calling \texttt{.move(3)} on a \texttt{Chipmunk} object would print this:
\begin{Verbatim}[fontsize=\small,samepage=true,frame=none]
tramp tramp tramp tramp tramp tramp
\end{Verbatim}
\index{encapsulation}
By the way, students often have a question here, and maybe you do too. They ask
whether they can call \texttt{super.super.move()} to invoke the ``grandparent's
method.'' The answer is \textbf{no}, for reasons having to do with
encapsulation. It's fine for a \texttt{Duck} to know it's a subclass of
\texttt{Bird}, but it shouldn't know what \texttt{Bird}'s superclass is, nor
even that \texttt{Bird} \textit{has} a superclass. That knowledge (which we
would be baking in to our program through a ``\texttt{super.super.}''\ call) is
outside the realm of the \texttt{Duck} class, and therefore should not be known
to it. If later, for instance, we refactor our code and make \texttt{Bird} its
own class instead of inheriting from \texttt{Animal}, \texttt{Duck} would break
if it had a ``\texttt{super.super.}''.
\subsubsection{Invoking a superclass's constructor with ``\texttt{super}'' (no
dot)}
\index{constructor}
\index{initialization}
You've known ever since p.~\pageref{page:instantiateConstructor} that whenever
an object is instantiated, one of that class's constructors is called. This is
indeed the case, but here's a new wrinkle: when an object is instantiated,
\textit{a constructor in its superclass is also called.} This is because in
order to ``set up'' the \texttt{Duck} stuff (initialize its inst vars,
\textit{etc.}), we also need to set up its \texttt{Bird} stuff, and for that
matter its \texttt{Animal} stuff. Since a \texttt{Duck} \textbf{is-a}
\texttt{Bird}, which in turn \textbf{is-a} \texttt{Animal}, it's imperative
that we have a valid \texttt{Animal} object before trying to make it a
special kind of \texttt{Animal} (and similarly, a valid \texttt{Bird} before
we make a special kind of \texttt{Bird}).
\index{student@\texttt{Student}}
\index{prof@\texttt{Prof}}
\index{person@\texttt{Person}}
This usually happens automatically, but can need some special coaxing if
you're passing arguments to constructors. An example is the code snippet in
Figure~\ref{fig:inhConstrCode} (whose class diagram is in
Figure~\ref{fig:inhConstrClass}). Here, the only constructor for the
\texttt{Person} class is one that takes a \texttt{String} argument; hence, we
must pass it a \texttt{String} if we want to instantiate one. In the
\texttt{Student} constructor (which takes a couple arguments of its own) we
call ``\texttt{super(name)}'' which passes the \texttt{name} the subclass was
given and passes it up to its superclass's constructor. In the
\texttt{Prof} constructor, we take a \texttt{"Dr.\ "} on to the front of
the name before passing it the superclass. Note that there's no ``dot'' after
these \texttt{super()}s; that's how we indicate we want to call the
constructor, rather than an ordinary method.
Somewhat weirdly, in Java the call to \texttt{super()} must be the
\textit{first} line of the constructor. That's because Java says, ``a
\texttt{Student} is a special type of \texttt{Person}. So if you want to be a
\texttt{Student}, you have to first be a fully-baked \texttt{Person}. Only
then will we get around to the \texttt{Student}-specific stuff.'' (Note this
restriction does \textit{not} apply to ``\texttt{super.}'' (``super dot'')
method calls; they can be put anywhere.)
\begin{figure}[ht]
\begin{Verbatim}[fontsize=\scriptsize,samepage=true,frame=single]
class Person {
private String name;
protected Person(String n) { class Prof extends Person {
this.name = n; private String dept;
} Prof(String n, String d) {
} super("Dr. " + n);
this.dept = d;
class Student extends Person { }
private double gpa; }
private int year;
Student(String name, int year) {
super(name);
this.gpa = 0.0;
this.year = 1; // Freshman
}
}
\end{Verbatim}
\caption{The interaction between constructors when inheriting.}
\label{fig:inhConstrCode}
\end{figure}
\index{protected@\texttt{protected}}
\index{subclass}
\index{abstract class}
One other thing on this \texttt{Person}/\texttt{Prof}/\texttt{Student}
example: we have defined the \texttt{Person} constructor to have
\textbf{\texttt{protected}} visibility. As you may recall from
Figure~\ref{fig:visibilityLevels} on p.~\pageref{fig:visibilityLevels},
\texttt{protected} visibility (denoted in UML with a hashtag) means that it
can only be called by a class in the same package \textit{or a subclass}. It's
useful in situations like this that involve inheritance: by making the
\texttt{Person} constructor \texttt{protected}, we're saying that no one
outside the package can instantiate a plain-old \texttt{Person}: instead they
must instantiate a subtype, which can then call the constructor from below.
This is related, but not quite the same, as declaring a method
\texttt{abstract}. (The difference being that \texttt{abstract} classes can't
be instantiated \textit{anywhere}, even in the same package.)
\begin{figure}
\centering
\includegraphics[width=0.9\textwidth]{inhConstrClass.pdf}
\caption{The class diagram for Figure~\ref{fig:inhConstrCode}.}
\label{fig:inhConstrClass}
\end{figure}
\section{Pure abstraction: Java interfaces}
\label{sec:interfaces}
\index{interface@\texttt{interface}}
We've now seen several examples of superclasses. Sometimes they have all
concrete (opposite of abstract) methods, and a subclass can pick and choose
which ones it wants to override. Sometimes, they have one or more
\texttt{abstract} methods, which the subclass \textit{must} override, or else
be un-instantiatable.
What if we push that idea all the way in the abstract direction: a ``pure''
abstract class, with only abstract methods? Is that any use?
\index{implements@\texttt{implements}}
Yes, and probably more than you realize right now. I'll get to the reasons
this is so powerful in a page or two, but for now let's just learn the syntax.
In Java, instead of a pure abstract class, you can create something called an
\textbf{interface}, which is essentially the same thing but which gives
considerable more flexibility. An interface is a template of sorts, with
\textit{no instance variables} and \textit{no method bodies}. Classes that
\textbf{implement} an interface promise to create a method body for each of
the methods in the interface.
\index{class@\texttt{class}}
In UML (see Figure~\ref{fig:interface}), an interface looks almost exactly
like a class. The only differences are: (1) there are
(sometimes\footnote{Designers aren't consistent about this, I've found. Some
do include all three compartments for an interface, even though the middle one
must by definition be empty.}) only two compartments instead of three, and (2)
the \textbf{stereotype} $\ll$interface$\gg$ appears in the name box (recall
``stereotypes'' from p.~\pageref{stereotype}).
\begin{figure}[ht]
\centering
\includegraphics[width=0.9\textwidth]{interface.pdf}
\caption{Two classes that implement interfaces.}
\label{fig:interface}
\end{figure}
\index{triangle ($\triangle$)}
\index{line!dashed (-\ -\ -)}
We indicate ``implements an interface'' with a \textit{dashed} line that
otherwise looks exactly like an inheritance arrow (recall
Figure~\ref{fig:inheritanceArrows} from p.~\pageref{page:inheritanceArrows}).
\index{storable@\texttt{Storable}}
\index{connection}
In Figure~\ref{fig:interface}, both of the classes in our racers
application need to store and load objects from the database. Hence, both of
them implement the \texttt{Storable} interface, which defines two methods, one
for storing and one for loading. The code for that much would look like:
\begin{Verbatim}[fontsize=\scriptsize,samepage=true,frame=single]
interface Storable {
void store(DBConn c);
void load(DBConn c);
}
class Race implements Storable { class Runner implements Storable {
private Date date; private String name;
private String loc; private String gender;
private int maxRunners; public void store(DBConn c) {
public void store(DBConn c) { ...
... }
} public void load(DBConn c) {
public void load(DBConn c) { ...
... }
} }
}
\end{Verbatim}
\index{runner@\texttt{Runner}}
\index{participant@\texttt{Participant}}
\index{register@\texttt{.register()}}
Some Java syntax idiosyncrasies: an \texttt{interface} has only method
signatures (return type, method name, parameter lists) followed by a
semicolon, just as with abstract methods. However, the methods are
\textit{not} marked as \texttt{abstract}, nor \texttt{public} nor anything
else. Note also that we don't say the class ``\texttt{extends}'' the interface,
but rather ``\texttt{implements}'' it.
In the same figure, we have \texttt{Runner} also implementing another
interface: \texttt{Participant}. Presumably there are also other types of
participants (volunteers, walkers, wheelchair racers, walkers, rock bands that
play on the sidewalks) that can \texttt{.register()} for races, and if they
want to be able to participate, their classes must implement this one-method
interface. We augment the code as follows:
\begin{Verbatim}[fontsize=\scriptsize,samepage=true,frame=single]
interface Participant {
int registerFor(Race r);
}
class Runner implements Storable, Participant {
private String name;
private String gender;
public void store(DBConn c) {
...
}
public void load(DBConn c) {
...
}
int registerFor(Race r) {
...
}
}
\end{Verbatim}
Take note of the fact that the \texttt{Runner} class definition has
\textit{two} \texttt{interface} names in its declaration line, separated by a
comma.
And that takes us, at last, to the reason Java \texttt{interface}s matter:
\textbf{\textit{because a class can implement more than one of them.}}
\index{inheritance!multiple}
\index{C++}
You might be thinking, ``okay, but couldn't we just have inherited from more
than one abstract class, and accomplished the same thing without this new
`interface' notion?'' The answer is \textbf{no}: Java does not allow
\textbf{multiple inheritance}, which is when a class has more than one
superclass. The reasons are somewhat lengthy to explain, and will be omitted
here, but suffice to say that languages that choose to support multiple
inheritance (C++ is among them) have some knotty problems to solve. For
instance, what if class \texttt{A} inherits from both \texttt{B} and
\texttt{C}, and both \texttt{B} and \texttt{C} have their own
\texttt{.doThis()} method. What code, then, would this line trigger?
\begin{Verbatim}[fontsize=\small,samepage=true]
A a = new A();
a.doThis(); <-- ? Whose "doThis()"?
\end{Verbatim}
How can it choose between \texttt{B}'s and \texttt{C}'s perfectly acceptable
implementations of \texttt{.doThis()}? Or should it run both of them, and if
so in what order?
\index{Gosling, James}
\index{inheritance!bottom-up (implementation)}
\index{inheritance!top-down (interface)}
James Gosling and the other designers of Java took a look at this problem and
decided that multiple inheritance wasn't worth the hassle. I happen to think
they were right, and for one simple reason: although programmers often want to
use multiple \textit{top-down} inheritance, they rarely want to use multiple
\textit{bottom-up} inheritance. And it's the latter that gives rise to all the
paradoxes and strange corner cases. As long as a class simply wants to
masquerade as one of several different things (as opposed to wanting to steal
method implementations and inst vars from more than one superclass), ``multiple
inheritance'' turns out not to be a big deal. One of Java's big wins was
allowing multiple interfaces to be implemented, not multiple classes to be
inherited from, thereby sidestepping the whole issue.
\begin{samepage}
So the bottom line is that in Java, a class can \textit{inherit} from only one
class, but it can \textit{implement} as many interfaces as it likes. If you do
both, you declare yourself like this:
\begin{Verbatim}[fontsize=\footnotesize,samepage=true,frame=single]
class Runner extends Athlete implements Participant, Storable {
...
}
\end{Verbatim}
\end{samepage}
Put another way, you only have one inheritance relationship to ``spend,'' so
use it wisely. Only inherit from something if it truly is an ``\textbf{is-a}''
relationship, and there's meaningful code you get to reuse by so doing.
\subsection{Example: \texttt{java.lang.Comparable}}
\index{comparable@\texttt{Comparable}}
\index{reservationSystem@\texttt{ReservationSystem}}
\index{resort@\texttt{Resort}}
Here's an example of the kind of thing that interfaces make easy. Recall our
\texttt{ReservationSystem} example from section~\ref{sec:resortExample} (on
p.~\pageref{sec:resortExample}). We had a class called \texttt{Resort} that
represented high-falutin' vacation destinations. It had inst vars like
\texttt{name}, \texttt{desc}, \texttt{phone}, \texttt{rating} (from 1 to 5
stars) and \texttt{cost} (from \$ to \$\$\$\$).
We also sketched a \texttt{ReservationSystem} class that would travel agents
to browse available rooms, book hotels for customers, \textit{etc.} We'll use
a \textbf{has-a} relationship for that (see Figure~\ref{fig:resortClass}).
\index{sort@\texttt{sort()}}
Now one of the things \texttt{ReservationSystem} is likely to want to do is
\textit{sort} the \texttt{Resort} objects in its list. There's a function in
\texttt{java.util.Collections} class called \texttt{sort()} that does just
that, in fact. We'd like to write code like this:
\begin{Verbatim}[fontsize=\small,samepage=true,frame=single]
class ReservationSystem {
private ArrayList<Resort> resorts;
...
private void printAvailableResorts() {
// Determine availability...
java.util.Collections.sort(resorts);
// Print results...
}
}
\end{Verbatim}
\begin{figure}[hb]
\centering
\includegraphics[width=0.9\textwidth]{resortClass.pdf}
\caption{Using the \texttt{Comparable} interface to enable sorting.}
\label{fig:resortClass}
\end{figure}
\index{collection!\texttt{Collections} class}
The trouble is, even though \texttt{Collections} has an efficient, bug-free
sorting algorithm all coded up for us to use, it doesn't know \textit{what
``sorted'' means for \texttt{Resort}s.} For a list of integers, we'd expect
``sorted'' to mean ``in numerical order.'' For \texttt{String}s, we'd expect
alphabetical order. But what about \texttt{Resort}s?
It turns out that \texttt{Collections.sort()} works for any collection of
objects that implement the \texttt{Comparable} interface from
\texttt{java.lang}. That interface has just one method, \texttt{.compareTo()},
which compares the object it's called on with another object. The
specification says it should return a negative number if \texttt{this} should
come before the argument in sorted order, and a positive number if the
argument should come first.
Let's say we want to sort our \texttt{Resort}s alphabetically by name. Then we
could just write:
\begin{Verbatim}[fontsize=\footnotesize,samepage=true,frame=single]
class Resort implements Comparable<Resort> {
private String name, desc, phone;
private int rating, cost;
...
public int compareTo(Resort r) {
return this.name.compareTo(r.name);
}
}
\end{Verbatim}
It's a weird-looking one-liner, but what this \texttt{.compareTo()}
implementation does is pass the buck to its \texttt{name} field. It says, in
effect, ``if you want to know whether I come before or after the resort
\texttt{r}, just look at whether my \texttt{name} comes before or after
\texttt{r}'s \texttt{name} alphabetically.''
Or, perhaps I want to sort by decreasing rating (5 stars first, 1 star last).
Then I could write:
\begin{Verbatim}[fontsize=\footnotesize,samepage=true,frame=single]
class Resort implements Comparable<Resort> {
private String name, desc, phone;
private int rating, cost;
...
public int compareTo(Resort r) {
return r.rating - this.rating;
}
}
\end{Verbatim}
Now, if I'm a 4-star hotel and \texttt{r} is a 2-star hotel, \texttt{r.rating
- this.rating} will be a negative number, putting me first.
You could detect equal ratings and break the tie by the cost, or sort by phone
number, reverse length of \texttt{desc}ription, or anything else you dream up.
The magic here is that we decoupled the sorting algorithm from the details of
how objects are compared. The \texttt{Collections.sort()} method is perfectly
happy as long as we keep our promise to implement \texttt{Comparable} and
provide a way to compare two \texttt{Resort} objects.
\section{\texttt{java.lang.Object}}
\index{object}
\index{C++}
\index{inheritance hierarchy}
\index{tree}
One other difference between C++ and Java is that Java has a
\textbf{single-rooted inheritance hierarchy}. This means that in Java, if you
trace \textit{any} class's ancestry up from superclass to superclass, you
eventually reach a common point. That point is called the \texttt{Object}
class from the \texttt{java.lang} package. \textit{All} classes, regardless of
who wrote them, are ultimately subtypes of \texttt{Object}.
It doesn't seem that way when we look at the code, since we saw
``\texttt{class Bear extends Animal}'' yet ``\texttt{class Animal}...(extends
nothing, presumably)''. But if you don't explicitly list a subtype via
\texttt{extends}, Java implicitly substitutes \texttt{Object} as the
superclass.
\index{equals@\texttt{.equals()}}
\index{toString@\texttt{.toString()}}
This has a couple of nice benefits. For one, there are methods on the
\texttt{Object} class that all objects are therefore guaranteed to inherit;
among them are \texttt{.equals()} and \texttt{.toString()}. For another, it is
possible to treat \textit{all} objects indistinguishably in certain contexts.
We saw this with the pre-generic collection classes like \texttt{ArrayList}.
The reason we can have a plain \texttt{ArrayList} hold absolutely anything --
say, two \texttt{String}s, three \texttt{Ballplayer}s and a \texttt{Duck} --
is that the list is treating them all as the ultimate supertype
(\texttt{Object}), in true top-down inheritance fashion. In C++ there isn't
really any way to do that, since if you have two classes that don't explicitly
inherit from a common type, then as Steely Dan says, they simply ``got nothing
in common.''