CS100M Lab Exercise 10


1. Defining Classes and Creating Objects

In this lab, you will learn about objects and classes. In particular, we will experiment with private and public methods and fields. We will define a Student class. First, let us create a class that represents a student. Create a file called Student.java in DrJava and type in the following code:
/* A Student has a name and a test score */
public class Student {

   public String name;  //we'll change the visibility modifier later
   public int testscore;
}
Now save the file and compile it. Then create another file named Lab10.java and put the following code in it:
public class Lab10 {

   public static void main(String[] args) {

      Student john= new Student();
      john.name= "John Doe";
      john.testscore= 55;
      System.out.println(john.name + " got a score of " + 
                         john.testscore + " on the exam.");
   }
}
Run the program and write down the screen output below.

ANS:



2. Protecting Fields

When we created the Student class, we made the two fields, name and testscore, public. This means that code outside of the Student class can freely modify those fields. In many cases, this is not a desirable result. For example, we may want to make sure that testscore always contains an integer between 0 and 100. Thus, we don't want code outside of the Student class to be able to set the testscore field to some invalid number, for example, -5. One way to do this is to make use of getters and setters (methods). Setters allow us to enforce certain rules by adding validity checking code before changing the fields.

Now, modify the Student class by making testscore a private field, and create a getter and a setter for it. Call them getTestscore and setTestscore respectively. In setTestscore, make sure that the passed argument is a valid value. If the argument is not in the acceptable range, simply set testscore to 0. Test your program by modifying the main method of class Lab10 to use the getter and setter methods:
public class Lab10 {

   public static void main(String args[]) {

      Student john = new Student();
      john.name = "John Doe";
      john.setTestscore(55);
      System.out.println(john.name + " got a score of " + 
                         john.getTestscore() + " on the exam.");
      john.setTestscore(-5);
      System.out.println(john.name + " got a score of " + 
                         john.getTestscore() + " on the exam.");
   }
}
Run the program and write down the screen output below.

ANS:



Now, modify the Student class to include a getter and a setter for the name field as well. Name the methods getName and setName respectively. Make the corresponding changes to class Lab10 and test your program.



3. ToString

We've used the println method to print primitive variable values before. Let's see what gets printed when you print the value of a reference variable. Add the following print statement to method main of Lab10.java:
      System.out.println(john);
Now run the program. The last thing printed is the reference ID of the object! This isn't the most useful information for us, so let's write a toString method in class Student to return the name and score of the student as a String. Then run Lab10 again. Now the statement System.out.println(john); uses the toString method that you have just defined to print the field values of the object instead of the reference ID of the object.



4. Using Getters and Setters with multiple objects

Now add more code to your main method in Lab10. Create three new students, Tom, Jerry, and Spike. Give Tom a random score in range of  0 to 100. Set Jerry's score to 20 below Tom's. Then set Spike's score to two times Jerry's. Finally, output the data of the three Student objects using a print statement. Below is the code for Tom and Jerry. Make sure you understand the code and then add more code for Spike.

      Student tom, jerry;
      tom = new Student();
      jerry = new Student();
      tom.setName("Tom");
      jerry.setName("Jerry");
      tom.setTestscore(1 + (int)(101 * Math.random()));
      jerry.setTestscore(tom.getTestscore() - 20);
      System.out.println(tom + "\n" + jerry);

Run the program Lab10 again and observe the result.

5. Constructor

Let's define a constructor for class Student:
   /* This Student has name s */
   public Student(String s) {
      setName(s);
   }
Now try to run your program again. This causes an error because the statements to create a Student object do not match the specification of the constructor--the constructor has a String parameter. Change the code in Lab10 to use the above constructor to create the object and set the name. Now the program should run without error.

Additional note: One might wonder why he or she could invoke new Student() before, even though there was no constructor Student() defined. The answer is that Java provides every class, ClassName, a default constructor of the form ClassName(), as long as the user hasn't defined one. However, if the user writes a constructor, the default constructor is no longer available.

6. Additional exercise

Download the latest Interval.java file from the Lecture Materials link and experiment with it! For example, write code in a main method in another class to create some Interval objects and call on their methods. If there is anything about that class that you don't understand, ask now!

Delete your files from the computer! (But you may want to email them to yourself for studying.)