Overview
This is an example of a problem we want to solve and the
difference between solving the problem in a procedural way vs. and
object-oriented way. The basic problem is read a file with
information on regular ol' people and midshipmen like this:
| in.txt |
6
pers Crabbe
midn Jones 250221 SDS
midn Ajax 242211 SCS
pers Fenske
midn Lee 264321 SCS
pers Brown |
And be able to print out the names like we would to begin a
letter, and of course to be able to print back the people in the
original format.
A thoroughly procedural approach
First let's look at a procedural approach to this ... the way you
might have done this in IC210 (except in Java):
-
Notice how instances of
Person may have unnecessary
fields (like "alpha" for people that are not actually mids).
-
Notice how we have to add the "kind" field to clue us in on what
kind of person we are dealing with: mid or regular
person.
-
Notice how the toString and salutation methods have to
switch on the "kind" field, and do different things
according to the particular kind of person.
All of these are indicators of not following object-oriented principles!
An object-oriented approach
When we "refactor" the above program to follow object-oriented
principles, we use inheritance to represent the idea that a "Mid"
is a special kind of "Person". This means no wasted, unnecessary
fields. We use polymorphism to make toString and salutation
perform differently for Mids than for regular ol' Persons.
See how much better encapsulated this is? All the code that is
Mid-specific is in the Mid class, separated away from the code
that is about regular old Persons. Where this really shines is
this: what if we want also allow for AthleteMids, which are just
like regular Mids except they also have a sport. This should'nt
change the salutation, but would change the toString. What
files have to change? Which files can stay untouched?