CS 160 Lab 3

Tuesday, February 3, 2004


Turn in your outlabs due today.

Objectives

Learn to design and use classes that include instance variables, constructors, methods and parameters.  Learn to design and apply programs that create objects from classes and manipulate those objects via methods

To Do (if you are comfortable with Java)

If you are comfortable with Java, you are to do exercise P2.17 at the end of chapter 2 in your book (page 76).  When you are finished, have the TA or one of the consultants check your work before you leave.

To Do (more help understanding Java)

Do the following.  If at any point you have questions be sure to ask for help from the TA or the consultants.  This is your opportunity to learn.

1.  Create a project called lab3 in BlueJ.

2.  Create a class called Student in that project.

3.  Replace the BlueJ contents of Student with the code below (cut and paste):

public class Student
{
   private String studentName;
   
   public void setName(String name)
   {
       studentName =  name;
   }
   
   public String getName()
   {
       return studentName;
   }
}

4.  Create a class called StudentTester in that project.

5.  Replace the BlueJ contents of StudentTester with the code below (cut and paste):

public class StudentTester
{
   public static void main(String[] args)
   {
       Student student1 = new Student();
       student1.setName("Jack");
       System.out.println(student1.getName());
   }
}

6.  Compile and run this program.

7.  Modify the class Student to have a constructor of the form

Student()

This constructor is to do nothing (it is the same as the default file). You may want to refer to your book to remind yourself of how to build a constructor.  Rerun the program.  You should get the same results as before

8.  Add a second constructor to class Student of the form

Student(String name)

This constructor is to create an object with the studentName instance field set to the name supplied by the call to the constructor.  Add statements to your main method in StudentTester to construct a new object called student2 with the name "Mary".  Use the constructor to set the name, not method setName.  Do not delete the statements already in main.  Compile and run the program.  You should see Jack and then Mary printed in the terminal window.

9.  Do the following series of modifications for this part:

10.  Show the results to the TA or one of the consultants.

11,  If you still have time left do exercise P2.8 at the end of chapter 2.  You can do this exercise just to be sure that you can write a program from scratch that contains a class for object construction and a tester class with a main method. If you don't have time to finish all three projects complete them during the week so you can have them all done at the beginning of next week's lab. Make sure your TA, or consultant checks off what you have done before you leave.


Outlab

Have all this completed by next week.