Top
Previous Next
The Java Language CS 161 - Java

Example of a Constructor

Source: examples/Student3c.java



/** Encapsulate information relating to a single student.
** @author: Jonathan Doughty
**/
 
public class Student3c {
 
 
public static void main(String args[]) {
Student3.tryIt();
Student3c.waitForUser(); // only needed for Windows/Javaedit
}
 
public static void tryIt() {
Student3c aStudent = new Student3c( "Jonathan Doughty",
"123-45-6789" );
aStudent.setGrade( 100 );
 
// When the preceding lines are executed, a Student3c 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;
 
// Constructors for the class
 
private Student3c() { // why do you think this is?
}
 
public Student3c( String name, String id) {
this.name = name;
GMU_Id = id;
}
 
// An accessor method to set the Student's name field; not
// needed any more but left in because a student's name could
// change.
public void setName( String studentName ) {
name = studentName;
}
 
// An accessor method to set the Student's GMU_Id field (probably
// no longer necessary)
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