Spring Semester 2003


Lab Notes Four: Classes and objects.

Let's start by mentioning a student 's observations, one past semester (it was Florentina Tone, if I remember correctly). It refers to how we calculate intersections of rectangles with the Java API. These are very perceptive observations. She said:

Hope you found these comments useful.

Let's go through the complete and annotated development of a solution to a problem.

(This is problem no. 5, below).

1. Let's implement a class Student.

frilled.cs.indiana.edu%pico Student.java
frilled.cs.indiana.edu%cat Student.java
public class Student {

} 
frilled.cs.indiana.edu%javac Student.java
frilled.cs.indiana.edu%ls -ld Student*
-rw-------   1 dgerman       188 Feb  1 08:18 Student.class
-rw-------   1 dgerman        27 Feb  1 08:17 Student.java
frilled.cs.indiana.edu%
2. Looks like we're done. Can we test it?

3. We need a tester class with a main method.

frilled.cs.indiana.edu%pico StudentTest.java
frilled.cs.indiana.edu%cat StudentTest.java
public class StudentTest {
  public static void main(String[] args) {
    Student a = new Student(); 
  } 
} 
frilled.cs.indiana.edu%javac StudentTest.java
frilled.cs.indiana.edu%ls -ld Student*
-rw-------   1 dgerman       188 Feb  1 08:18 Student.class
-rw-------   1 dgerman        27 Feb  1 08:17 Student.java
-rw-------   1 dgerman       297 Feb  1 08:21 StudentTest.class
-rw-------   1 dgerman       110 Feb  1 08:21 StudentTest.java
frilled.cs.indiana.edu%
4. Can we test it?

5. We can run StudentTest but we get no output.

frilled.cs.indiana.edu%java StudentTest
frilled.cs.indiana.edu%
6. Does it matter?

7. Do we know what happens inside?

8. The Student class is empty. Student objects are amorphous.

9. I see... Let's make it such that each Student has (at least) a name, then.

frilled.cs.indiana.edu%pico Student.java
frilled.cs.indiana.edu%cat Student.java
public class Student {
  private String name; 

} 
frilled.cs.indiana.edu%
10. What's the meaning of private?

11. It means that to know the name of a Student you need to ask the Student what its name is.

12. I don't feel very comfortable using he or she for a Student object.

13. Fine. How do you inquire about a Student's name?

14. We need to add this functionality to class Student first, then make use of it.

15. Here's a more comprehensive blueprint of Student objects.

frilled.cs.indiana.edu%pico Student.java
frilled.cs.indiana.edu%cat Student.java
public class Student {
  private String name; 

} 
frilled.cs.indiana.edu%pico Student.java
frilled.cs.indiana.edu%cat Student.java
public class Student {
  private String name; 

  public String whatsYourName () {
    return name; 
  }

} 
frilled.cs.indiana.edu%
16. What does it mean for the whatsYourName method to be public?

17. It means you can ask a Student "What's your name?"

18. What if we make it private?

19. Then we can never ask.

20. How do we create a Student?

21. Just invoke new the way we did in the tester's main.

22. And if we invoke it, how do things get created, and initialized.

23. Well, a default no-arg constructor is present, but we don't see it.

24. I think we should add it, so that we not forget that it's there.

frilled.cs.indiana.edu%pico Student.java
frilled.cs.indiana.edu%cat Student.java
public class Student {
  private String name; 

  public String whatsYourName () {
    return name; 
  }

  Student() {

  } 
} 
frilled.cs.indiana.edu%
25. It's empty, but it gets called at creation time.

26. Can we create a Student with an initial name?

27. Only if we provide that type of constructor.

28. To be able to create a Student with an initial name we need to

29. We're looking for something like this:
new Student("Larry Johnson")
30. Let's provide class Student with that capability.

frilled.cs.indiana.edu%pico Student.java
frilled.cs.indiana.edu%cat Student.java
public class Student {
  private String name; 
  public String whatsYourName () {
    return name; 
  }
  Student() { } 
  Student(String givenName) {
    name = givenName;     
  }
} 
frilled.cs.indiana.edu%
31. Let's enhance our tester's main to exploit the new features.

frilled.cs.indiana.edu%pico StudentTest.java
frilled.cs.indiana.edu%cat StudentTest.java
public class StudentTest {
  public static void main(String[] args) {
    Student a = new Student("Larry");
    Student b = new Student("Michael");
    String answer; 
    System.out.print("Printing the name of the first student: "); 
    answer = a.whatsYourName(); 
    System.out.println(answer); 
    System.out.print("Printing the name of the second student: "); 
    answer = b.whatsYourName(); 
    System.out.println(answer); 
  } 
} 
frilled.cs.indiana.edu%javac StudentTest.java
frilled.cs.indiana.edu%java StudentTest
Printing the name of the first student: Larry
Printing the name of the second student: Michael
frilled.cs.indiana.edu%
32. Great! What else were we supposed to do?

33. Let's enable the Students to keep track of their scores.

frilled.cs.indiana.edu%pico Student.java
frilled.cs.indiana.edu%cat Student.java
public class Student {
  private String name; 
  public String whatsYourName () {
    return name; 
  }
  Student() { } 
  Student(String givenName) {
    name = givenName;     
  }
  void addQuizScore(int newScore) {
    totalScore = totalScore + newScore; 
  } 
  private int totalScore; 
} 
frilled.cs.indiana.edu%
34. I see... If there's a new score to be added to the total score for a student then we just add it to the totalScore as if it were an amount to be placed as deposit over a current, given, existing balance.

35. Yes, so you need to define an instance variable totalScore (which will keep the cumulative score for the Student) and use it as if it were a balance.

36. This way a Student is like a BankAccount with a name.

37. Let's write getBalance, then.

frilled.cs.indiana.edu%pico Student.java
frilled.cs.indiana.edu%cat Student.java
public class Student {
  private String name; 
  public String whatsYourName () {
    return name; 
  }
  Student() { } 
  Student(String givenName) {
    name = givenName;     
  }
  void addQuizScore(int newScore) {
    totalScore = totalScore + newScore; 
  } 
  private int totalScore; 
  int whatsYourTotalScore() {
    return totalScore; 
  }
} 
frilled.cs.indiana.edu%
38. Let's test it.

frilled.cs.indiana.edu%pico StudentTest.java
frilled.cs.indiana.edu%cat StudentTest.java
public class StudentTest {
  public static void main(String[] args) {
    Student a = new Student("Larry");
    Student b = new Student("Michael");
    String answer; 
    System.out.print("Printing the name of the first student: "); 
    answer = a.whatsYourName(); 
    System.out.println(answer); 
    System.out.print("Printing the name of the second student: "); 
    answer = b.whatsYourName(); 
    System.out.println(answer); 

    a.addQuizScore(100); 
    a.addQuizScore(90); 
    a.addQuizScore(100); 
    System.out.println("Student " + a.whatsYourName() + "reports: "); 
    System.out.println("   cumulative score: " + a.whatsYourTotalScore());

  } 
} 
frilled.cs.indiana.edu%javac StudentTest.java
frilled.cs.indiana.edu%java StudentTest
Printing the name of the first student: Larry
Printing the name of the second student: Michael
Student Larryreports: 
   cumulative score: 290
frilled.cs.indiana.edu%
39. I think you need a space between Larry and reports.

40. I'll let you fix that. But overall we've come a long way, don't you think?

41. I sure do think so. What if I want the Students to be able to report the average score in addition to the cumulative score? I don't think this is possible at the moment, because they don't remember how many quizzes they have taken.

42. Indeed, they only keep the cumulative score.

43. To remember how many quizzes they have taken they would need to keep a counter, to be updated (incremented by 1) every time a new score is added to the totalScore.

44. If we kept the number updated we could easily report the average at any time, as follows.

frilled.cs.indiana.edu%pico Student.java
frilled.cs.indiana.edu%cat Student.java
public class Student {
  private String name; 
  public String whatsYourName () {
    return name; 
  }
  Student() { } 
  Student(String givenName) {
    name = givenName;     
  }
  void addQuizScore(int newScore) {
    totalScore = totalScore + newScore; 
  } 
  private int totalScore; 
  int whatsYourTotalScore() {
    return totalScore; 
  }
  private int numberOfScores; 
  double reportAverage() {
    return (double)totalScore / numberOfScores; 
  }   
} 
frilled.cs.indiana.edu%
45. I think you forgot to update the counter in addQuizScore, haven't you?

46. Ooops!...

frilled.cs.indiana.edu%pico Student.java
frilled.cs.indiana.edu%cat Student.java
public class Student {
  private String name; 
  public String whatsYourName () {
    return name; 
  }
  Student() { } 
  Student(String givenName) {
    name = givenName;     
  }
  void addQuizScore(int newScore) {
    totalScore = totalScore + newScore; 
    numberOfScores = numberOfScores + 1; 
  } 
  private int totalScore; 
  int whatsYourTotalScore() {
    return totalScore; 
  }
  private int numberOfScores; 
  double reportAverage() {
    return (double)totalScore / numberOfScores; 
  }   
} 
frilled.cs.indiana.edu%
47. There you go.

48. Can you test that?

49. Sure, how about this:

frilled.cs.indiana.edu%pico StudentTest.java
frilled.cs.indiana.edu%cat StudentTest.java
public class StudentTest {
  public static void main(String[] args) {
    Student a = new Student("Larry");
    Student b = new Student("Michael");
    String answer; 
    System.out.print("Printing the name of the first student: "); 
    answer = a.whatsYourName(); 
    System.out.println(answer); 
    System.out.print("Printing the name of the second student: "); 
    answer = b.whatsYourName(); 
    System.out.println(answer); 

    a.addQuizScore(100); 
    a.addQuizScore(90); 
    a.addQuizScore(100); 
    System.out.println("Student " + a.whatsYourName() + "reports: "); 
    System.out.println("   cumulative score: " + a.whatsYourTotalScore());
    System.out.println("   average score:    " + a.reportAverage());

  } 
} 
50. Nice. You only changed one line!

51. Indeed. And here's the actual test:

frilled.cs.indiana.edu%javac StudentTest.java
frilled.cs.indiana.edu%java StudentTest
Printing the name of the first student: Larry
Printing the name of the second student: Michael
Student Larryreports: 
   cumulative score: 290
   average score:    96.66666666666667
frilled.cs.indiana.edu%
52. Good Student!

53. Yes. Isn't it time for a break?

54. I sure think so.

55. See you next week!

Until then, here's a brief summary of chapter 4:

Here are some problems for you to practice with (in preparation of your next week's lab assignment).

Try to solve these problems to practice some of the things you learned this week. In the examples that follow, your program's answers are always in blue, to distinguish them from what you would type as a user. Remember: the resulting programs are elementary, and the problems are interesting.

1. Write a program that asks for an initial balance amount. Create a BankAccount object with that amount. Then ask for a deposit amount and a withdrawal amount. Carry out the deposit and withdrawal, then print the remaining balance. Use ConsoleReader from Lab Notes Two, and please place your main method in the class BankAccount.
Here's a sample run of such a program:
frilled.cs.indiana.edu%javac BankAccount.java
frilled.cs.indiana.edu%java BankAccount
Hello, and welcome to JavaOne Bank.
An account will be created for you.
What will the initial balance be?
Type it now: 
-40.2
The current balance in your account is: -40.2
You now want to make a deposit. How much?
Type the amount here: 
120.3
The current balance in your account is: 80.1
You now want to make a withdrawal. How much?
Type it now: 
34
The current balance in your account is: 46.099999999999994
Thanks for using class BankAccount. Good-bye!
frilled.cs.indiana.edu%


2. Implement a class Employee. An employee has a name (a String) and a salary (a double). Write a default constructor, a constructor with two parameters (name and salary), and methods to return the name and salary. Write a small program to test your class.
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Employee
Creating a new employee.
Please type the name:
Larry Bird
Please specify the salary:
200000
New employee has been created.
Name of employee: Larry Bird
Salary: 200000.0
Thank you for testing class Employee.
frilled.cs.indiana.edu%

3. Implement a class Employee. An employee has a name (a String) and a salary (a double). Write a default constructor, a constructor with two parameters (name and salary), and methods to return the name and salary. Test your program, then enhance the class by adding a method
raiseSalary(double byPercent)
that raises the employee's salary by a certain percentage.
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Employee
Creating a new employee.
Please type the name:
Michael Jordan
Please specify the salary:
300000
New employee has been created.
Name of employee: Michael Jordan
Salary: 300000.0
Raising the salary of Michael Jordan
By what percentage (e.g., 10, 20, etc.)?
10.5
Name of employee: Michael Jordan
Current salary: 331500.0
Thank you for testing class Employee.
frilled.cs.indiana.edu%

4. Implement a class Car with the following properties. A car has a certain fuel efficiency (measured in miles per gallon or liters per km -- pick one) and a certain amount of fuel in the gas tank. The efficiency is specified in the constructor,and the initial fuel level is 0. Supply a method drive that simulates driving the car for a certain distance, reducing the fuel level in the gas tank, and methods getFuelLevel, returning the current fuel level, and tank, to tank up.
Sample usage of the class:
public static void main(String[] args) {
  Car myBeemer = new Car(29);
  System.out.println(myBeemer.getFuelLevel()); 
  myBeemer.tank(20); 
  System.out.println(myBeemer.getFuelLevel()); 
  myBeemer.drive(100); 
  System.out.println(myBeemer.getFuelLevel()); 
} 
Should produce:
frilled.cs.indiana.edu%java Car
0.0
20.0
16.551724137931036

5. Implement a class Student. For the purpose of this exercise, a student has
  • a name and
  • a total quiz score
Supply an appropriate constructor and methods
  • getName()
  • addQuiz(int score)
  • getTotalScore(), and
  • getAverageScore()

To compute the latter, you also need to store the number of quizzes that the student took.

Here's a sample run of such a program:
public static void main(String[] args) {
    Student a = new Student("Larry"); 
    a.addQuiz(10);
    a.addQuiz(9); 
    a.addQuiz(8); 
    System.out.println("Grade report for: " + a.getName()); 
    System.out.println("Total score: " + a.getTotalScore()); 
    System.out.println("Average score: " + a.getAverageScore()); 
}
Should produce:
frilled.cs.indiana.edu%java Student
Grade report for: Larry
Total score: 27.0
Average score: 9.0
frilled.cs.indiana.edu%

6. Implement a class Product. A product has
  • a name and
  • a price
For example
new Product("Toaster", 29.95)
Supply methods
  • printProduct()
  • getPrice(), and
  • setPrice()
Write a program that
  • makes two products,
  • prints them,
  • reduces their prices by $5.00, and then
  • prints them again
Here's a sample run of such a program:
public static void main(String[] args) {
    Product a = new Product("Toaster", 29.95); 
    Product b = new Product("Phone", 35.55); 
    a.printProduct(); 
    a.setPrice(a.getPrice() - 5.00); 
    a.printProduct(); 
    b.printProduct(); 
    b.setPrice(b.getPrice() - 5.00); 
    b.printProduct(); 
} 
Should produce:
frilled.cs.indiana.edu%java Product
Product name: Toaster
Product price: 29.95
------------------------------
Product name: Toaster
Product price: 24.95
------------------------------
Product name: Phone
Product price: 35.55
------------------------------
Product name: Phone
Product price: 30.549999999999997
------------------------------
frilled.cs.indiana.edu%

7. Implement a class Circle that has methods
  • getArea() and
  • getCircumference()
In the constructor, supply the radius of the circle.
Here's a sample run of such a program:
public static void main(String[] args) {
    ConsoleReader c = new ConsoleReader(System.in); 
    System.out.println("Please specify the radius of your circle:"); 
    Circle a = new Circle(c.readDouble()); 
    System.out.println("Circle created. "); 
    System.out.println("Area: " + a.getArea()); 
    System.out.println("Circumference: " + a.getCircumference()); 
    System.out.println("Good-bye!"); 
}
Should produce:
frilled.cs.indiana.edu%java Circle
Please specify the radius of your circle:
1.0
Circle created. 
Area: 3.141592653589793
Circumference: 6.283185307179586
Good-bye!
frilled.cs.indiana.edu%java Circle
Please specify the radius of your circle:
3.14
Circle created. 
Area: 30.974846927333928
Circumference: 19.729201864543903
Good-bye!
frilled.cs.indiana.edu%

8. Implement a class BeerCan with methods
  • getSurfaceArea() and
  • getVolume()
In the constructor, supply the height and radius of the can.
Here's a sample run of such a program:
public static void main(String[] args) {
    ConsoleReader c = new ConsoleReader(System.in); 
    System.out.println("Please specify the height of the BeerCan."); 
    double height = c.readDouble(); 
    System.out.println("Please specify the radius of the BeerCan."); 
    double radius = c.readDouble(); 
    BeerCan b = new BeerCan(height, radius); 
    System.out.println("The BeerCan has been created."); 
    System.out.println("Its surface area is: " + b.getSurfaceArea()); 
    System.out.println("Its volume is: " + b.getVolume()); 
}
Could produce:
frilled.cs.indiana.edu%java BeerCan
Please specify the height of the BeerCan.
2.5
Please specify the radius of the BeerCan.
1.0
The BeerCan has been created.
Its surface area is: 15.707963267948966
Its volume is: 7.853981633974483
frilled.cs.indiana.edu%java BeerCan
Please specify the height of the BeerCan.
2
Please specify the radius of the BeerCan.
1
The BeerCan has been created.
Its surface area is: 12.566370614359172
Its volume is: 6.283185307179586
frilled.cs.indiana.edu%

Good luck and don't forget: the harder they seem the more you can learn from them.

But these problems are not difficult. They're just that: good practice.


Last updated: Jan 27, 2004 by Adrian German for A201