Java Reference
In-Depth Information
adding Methods to the Course and Student Classes 
try it out
You will use the Student class definition to add a number of methods.
1.
Open the Student.java class you defined in the previous Try It Out in Eclipse, or create a blank
class if you haven't done so already.
2.
Modify the class definition so that it looks as follows:
class Student {
int id;
String firstName;
String lastName;
int birthYear, birthMonth, birthDay;
boolean isBirthday() {
// Return true if it's the student's birthday today.
return false;
}
void giveWarning(boolean isFinalWarning) {
// You should study harder!
}
int numberOfFriends() {
// Return the number of friends the student has.
return 0;
}
}
How It Works
Now take a look at how it works.
1.
In the source code of this class, you have now added three method definitions: for isBirthday ,
giveWarning , and numberOfFriends , respectively.
2.
Each of these methods starts with a return type ( boolean , int , or void when no return type is
expected), the name of the method, and a number of arguments the method takes as inputs.
3.
The method bodies do not look particularly interesting as of now, and just return a value immedi-
ately or do nothing.
4.
Again, you're not running this code yet, but feel free to add more method definitions for the Student
and Course classes. If you're up to it, you can also try adding some code to the method bodies.
Again, if you've followed along with the Try It Out, you'll recognize the same pattern showing up
for each method definition. That is, methods start with a return type, followed by the name of the
method, and then a number of arguments the method takes as inputs (for example, the isFinal-
Warning argument for the giveWarning method). Just as with variables, recall that method names
are written in lowerCamelCase . The method's “body” is surrounded by curly brackets, { and } , just
as for classes. Note that this creates a hierarchy: methods are defined within the class body, and the
code for the method itself is defined within the method body.
Search WWH ::




Custom Search