Task - Defining a Student class
The below illustration will explain how to write a class. We want to write a "Student" class which
- should be able to store the below characteristics of student
- Roll No
- Name
- Provide default, parameterized and copy constructors
- Provide standard getters/setters (discuss shortly) for instance variables
- Make sure, roll no has never assigned a negative value i.e. ensuring correct state of object
- Provide print method capable of printing student object on console
Getters / Setters
Attributes of a class are usually taken as private or protected. So to access them outside of a class, a convention is followed knows as getters & setters. These are usually public methods. Words set and get are used prior to name of an attribute. Another significant purpose for writing getter & setters to control the values assigned to an attribute.
Student Class Code
// File Student.java
public class Student {
private String name;
private int rollNo;
// Standard Setters
public void setName (String name) {
this.name = name;
}
// Note the masking of class level variable rollNo
public void setRollNo (int rollNo) {
if (rollNo > 0) {
this.rollNo = rollNo;
}else {
this.rollNo = 100;
}
}
// Standard Getters
public String getName ( ) {
return name;
}
public int getRollNo ( ) {
return rollNo;
}
// Default Constructor public Student() {
name = "not set";
rollNo = 100;
}
// parameterized Constructor for a new student
public Student(String name, int rollNo) {
setName(name); //call to setter of name
setRollNo(rollNo); //call to setter of rollNo
}
// Copy Constructor for a new student
public Student(Student s) {
name = s.name;
rollNo = s.rollNo;
}
// method used to display method on console
public void print () {
System.out.print("Student name: " +name);
System.out.println(", roll no: " +rollNo);
}
} // end of class