Top
Previous Next
The Java Language CS 161 - Java

A Student Object that identifies itself

Source: examples/Student3.java



/** Encapsulate information relating to a single student.
** @author: Jonathan Doughty
**/
 
public class Student3 {
 
 
public static void main(String args[]) {
Student3.tryIt();
Student3.waitForUser(); // only needed for Windows/Javaedit
}
 
public static void tryIt() {
Student3 aStudent = new Student3();
 
aStudent.setName("Jonathan Doughty");
aStudent.setId("123-45-6789");
aStudent.setGrade( 100 );
 
// When the preceding lines are executed, a Student3 object is
// created and its two fields are set.
 
// Does the following do something different? What does the
// result look like now?
System.out.println(aStudent);
}
 
// Instance variables (fields) that will be associated with
// each student
 
private String GMU_Id;
private String name;
private int homeworkGrade;
 
// An accessor method to set the Student's name field
public void setName( String studentName ) {
name = studentName;
}
 
// An accessor method to set the Student's GMU_Id field
public void setId( String id ) {
GMU_Id = id;
}
 
// An accessor method to set the Student's homeworkGrade field
public void setGrade( int grade ) {
homeworkGrade = grade;
}
 
// Using the toString method to enable an instance of an
// object to identify itself usefully.
public String toString() {
String result = name + ":" + GMU_Id + " grade:" + homeworkGrade;
return result;
}
 
// The following is only needed for running the program from
// within the Javaedit application on Windows
public static void waitForUser() {
try {
byte[] line = new byte[80];
System.out.println("press enter key to end");
System.in.read(line);
}
catch (java.io.IOException e) {
// ignored
}
}
}


Top
Previous Next
jwd