| CSC 207 | Algorithms and Object Oriented Design | Spring 2010 |
Summary: In this lab, you will explore inheritance in Java by building and extending some simple classes.
mkdir somewhere/inheritance
cd somewhere/inheritance
cp ~weinman/public_html/courses/CSC207/2010S/labs/code/inheritance/WhatCounts.java .
Counter that will
allow clients to build objects that count things, starting at some
value.
The class should contain
int fields called count
and start.
count and
start to that value.
increment(), which adds 1 to count
(the increment method should indicate that it may
throw
an IllegalStateException);
reset(), which resets count to
start;
toString(), which returns a string of the
form [nnn]];
value(), which returns the value of count
WhatCounts.java
that you copied in the lab preparations.
DecrementableCounter, that has
the following form:
public class DecrementableCounter
extends Counter
{
public DecrementableCounter(int start)
{
super(start);
} // DecrementableCounter(int)
} // class DecrementableCounter
gamma
in WhatCounts.java so that it reads
Counter gamma = new DecrementableCounter(-5);
decrement() method
to DecrementableCounter This method should subtract
one from the count field.
WhatCounts to test that method.
gamma so that it reads
DecrementableCounter gamma = new Counter(-5);
gamma to
Counter gamma = new DecrementableCounter(-5);
public class NamedCounter
extends Counter
{
String name;
public NamedCounter(String name, int start)
{
super(start);
this.name = name;
} // NamedCounter(String, int)
} // class NamedCounter
WhatCounts so that the initialization of
alpha reads
Counter alpha = new NamedCounter(0);
NamedCounter.
WhatCounts.
toString method by inserting the
following code into NamedCounter
public String toString() {
return this.name + super.toString();
} // toString()
NamedCounter and determine what errors, if any,
you get. Why do you think that is?
DoubleCounter, that has the
following form:
public class DoubleCounter
extends Counter
{
} // class DoubleCounter
DoubleCounter of the
following form
public DoubleCounter(int start)
{
super(start);
} // DoubleCounter(int)
WhatCounts so that the initialization of
beta reads
Counter beta = new DoubleCounter(123);
increment method by inserting the
following code
into DoubleCounter
public void increment()
{
super.increment();
super.increment();
}
Counter called
LimitedCounter
that includes
int field named limit;
limit
field); and
increment method that throws an
IllegalStateException when count
exceeds limit.
gamma to
Counter gamma = new LimitedCounter(-5,3);
LimitedCounter a subclass
of DoubleCounter rather than a subclass
of Counter. (That is, change the line that
reads extends Counter to read
extends DoubleCounter.)