home—info—lects—labs—exams—hws
tutor/PIs—Object120 + its docs—java.lang docs—java.util docs
lect07a
data design with objects
- review:
- exam info
- how to access fields
- static fields / named constants;
- meaning of 'static',
- purpose of constructor
Case Study:
How to represent a Pizza?
-
What fields?
-
How to represent toppings?
Don't use a flat string.
In reality we'd use a list-of-Strings (or, array-of-Strings);
for now we'll declare every Pizza has exactly two toppings
(never more, never less).
-
Write the constructor.
Be careful to distinguish between the fields and the parameter names!
What does the picture look like, when calling a constructor?
As always there are parameters that get auto-initialized;
because we are a constructor there is an extra, implcicit
variable named “this” which
is initialized to (point to) an empty object.
The purpose of a constructor: make sure all fields get initialized.
-
If we *did* want to include code which keeps bad toppings
from being used, where would we add such a check?
In the constructor.
We'll write some code.
We see that this leads to
(a) a helper function isValidTopping,
(b) questions on using ||,
(c) understanding the error-message about
“equals(Object) cannot be applied to String,String”;
recall that we'll want to use Object120.equals.
And, if we want equals to work for entire Pizzas
(so that our test cases work),
we should really extend Object120
(in which case we don't need to specify the full
name when calling equals).
-
What to do in case of error?
Print to System.err is plausible.
-
Either: initialize the field to a safe value (e.g. always "mushroom" if passed a bad topping), or
-
Trigger an error:
either divide by zero (e.g. int causeError= 1/0;),
or in ITEC220 we'll see that you might actually
throw new RuntimeException( "a descriptive message here" ).
Note the use of “new” —
in Java, errors are themselves objects!
You'll learn about “throw”
(and its complement “catch”) in ITEC220.
-
Why should CRUST_WIDTH be a named constant?
Because it never depends on the individual pizza's size, toppings, etc.
(At least not in our simple model.)
We declare the field to be static,
and we must initialize it on the same line we declare it.
home—info—lects—labs—exams—hws
tutor/PIs—Object120 + its docs—java.lang docs—java.util docs