Write a class Student
that represents, of course, a student. The attributes that a student should have (implemented as instance variables) are:
You will also implement these methods:
equals()
: checks if two students are the sameisOlder
: checks if one student is older than the otherisInSameMajor()
: checks if one student is in the same major as the otherAfter implementing the class, test it by creating Student
objects in a separate test class’s main()
method, and calling methods on these objects. For example:
// create objects for
Student s1 = new Student();
Student s1 = new Student();
// setup attribute values
s1.setName("John");
s1.setAge(23);
s1.setID(13234);
s1.setMajor("Computer Science");
s2.setName("Jane");
s2.setAge(22);
s2.setID(23472);
s2.setMajor("Accounting");
// do comparisions
if (s1.equals(s2))
System.out.println("The two objects represent the same student.");
else
System.out.println("The two objects represent different students.");
if (s1.isOlder(s2))
System.out.println(s1.getName() + " is older than " + s2.getName());
else
System.out.println(s1.getName() + " is younger than " + s2.getName());
if (s1.isInSameMajor(s2))
System.out.println(s1.getName() + " is in same major as " + s2.getName());
else
System.out.println(s1.getName() + " and " + s2.getName() + " are in different majors.");
public class Student {
String name;
int age;
int id;
String major;
/**
* Accessors and mutators for all attributes
*/
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setMajor(String major) {
this.major = major;
}
public String getMajor() {
return major;
}
/**
* Comparison methods
*/
public boolean equals(Student anotherStudent) {
if (name.equals(anotherStudent.name) && id == anotherStudent.id)
return true;
else
return false;
}
public boolean isInSameMajor(Student anotherStudent) {
if (major.equals(anotherStudent.major))
return true;
else
return false;
}
public boolean isOlder(Student anotherStudent) {
if (age > anotherStudent.age)
return true;
else
return false;
}
}