In-class exercise: Methods
October 3, 2008
Description
The purpose of this exercise is to give you some practice in writing methods in classes.Download StudentStats.java and
Student.java. Make sure they are both
in the same directory on your computer. Read through both files and try to
understand what is happening. Note that StudentStats.java contains a main
method and is the main program that will be run. Try to compile both files. You will
get some compiler errors. Your goal is to fix Student.java so that it is error-free.
Once you have fixed the errors, you can recompile both files and run the program
(make sure you are in the StudentStats.java window when you try to run the program).
There are five things that you will be required to do. For the first four items,
follow the getName
and setName
methods as examples. Note
that all of the instance variables in the class Student
are declared as
private
. This means that you cannot directly access these variables
from outside the class Student
(for example, if you have an object of
type Student
named jack
you cannot write jack.major
).
The methods, however, are all declared public
.
Fill in the code for the getMajor
method in Student.java.
Fill in the code for the setMajor
method in Student.java.
Fill in the code for the getAge
method in Student.java.
Fill in the code for the setAge
method in Student.java.
Write the code for the increaseYear
method in Student.java.
increaseYear
method. Look at the code at the bottom of StudentStats.java
to see how the increaseYear
method is being called (the code is
currently commented out). Note: after you write your
increaseYear
method, uncomment the code at the bottom of
StudentStats.java to test your increaseYear
method. Reference pp.
243-249 (4th edition) or 262-267 (5th edition) if you have any questions.
This exercise will not be graded. We will discuss it later. You are welcome to work in groups, but make sure you understand the concepts. Ask questions if you are having trouble.