Defining new classes
We looked at the ClassyBasketball example and discussed how to
implement it by defining a new BBall class which encapsulates all
the things that we want the ball to be and to do in ClassyBasketball.
Click to see the applet and code: ClassyBasketball
We then discussed, more generally, how to define a new class.
The structure of a class is as follows:
public class Name
{
constant and instance variable declarations
constructor definition(s)
method definitions
}
When we define a new class:
- We must declare whatever instance variables will be
necessary to describe the parts and state of an object of that
class. Any individual basketball is composed of ovals, lines and
arcs so the instance variable of the BBall class refer to these
objects.
- We need to provide a special method called a constructor. We've been using constructors for our library
objects - whenever we write a construction. When we say new
FramedRect, Java knows what to do to make a
FramedRect appear on the screen because someone defined a
constructor for FramedRect. When we write a
constructor, we will write a list of statements to construct the
components of the object desired (the parts of the basketball) and
associate the with instance variables defined in the new class.
- We need to define methods - i.e., lists of statement
explaining how to perform the actions we want the new objects to
know how to do.
Notice the differences between the move and contains method in
BBall. Also notice how moveTo cleverly uses the
move method of the class via writing
this.move(...,...).