Creating the project
Start your favorite IDE.
Create a project with a name of your choosing.
Start by creating a Java application (a class
with a main method)
with the class name TestDriver
within the package edu.unca.cs.csci202 .
Have your main method print something like
"Today it will snow!".
Creating a second class
Create a second class, called Place,
within the same package.
Place is a subclass of Object,
so you do not need to use extends.
Place has no public fields.
Place has four public methods.
getNamereturns aString, the name of the placegetStatereturns aString, the state where the place is locatedsetNametakes aStringas an argument and sets the name of a placesetStatetakes aStringas an argument and sets the state for the place
Be sure to define fields to contain the name and state for Place.
Initialize both fields to "".
In the terminology of object-oriented programming, the “get” methods are known at accessor, or getter, methods and the the “get” methods are known at mutator, or setter, methods.
Using the new class
Go back to TestDriver
Add code to create a variable hazelwood
Set the name of hazelwood to
"Hazelwood" and the state to "NC".
Use System.out.println to print the value of
hazelwood. (The default
toString will be used.)
Go back to Place and add a constructor that takes two arguments,
Strings corresponding to name and state, in that order.
Return to TestDriver. Oops, looks like a problem with the
constructor used to create hazelwood. Java provides its own
default constructor until you define one of your own. Then
Java takes the old one away. That is strange.
So, add a default constructor and, just for fun, call
the this constructor
to initialize both fields to "".
Now TestDriver is happy.
Use your new constructor to create a Place
variable frogLevel with name
"Frog Level" and state "NC".
And, again use System.out.println to print
frogLevel.
Examining the modifiers
If you are using NetBeans, select Place.java in the Projects tab and take a look at the Member View in the lower left corner.
Notice the little icons in front of constructor, method, and field names.
Change the access modifiers in front of the members (choices are
public,
private, and protected)
and see how the icons are changed.
Overriding
Override the toString method so that the
Place object will return values similar to
"Frog Level, NC".