The starter code has a Student.java file with the outline of a Student class. Th
ID: 3746721 • Letter: T
Question
The starter code has a Student.java file with the outline of a Student class. This class already has member variables firstName, lastName and studentId. Notice that the member variables are private, so other classes may not read or write them. But within the Student class all the private & public variables are treated the same.
Your task is to create methods to get and set all three of these values, so that other classes have a way to read and write the student's name and ID.
1. All your methods will be public.
2. All your methods will be non-static (omit the static keyword).
3. Create methods setFirstName(), setLastName() and setStudentId() to set the values of firstName, lastName and studentId, respectively.
4. Each of these "setter" methods has no return value.
5. Each of these "setter" methods must have one input parameter of the same type as the member variable it is going to set.
6. Each of these "setter" methods assigns the input parameter to the member variable.
7. For the "getter" methods getFirstName(), getLastName(), getStudentId(), there are no input parameters.
8. Each of the getters has a single return value of the same type as the member variable it reads.
9. Each of the getters returns the member variable, for instance getStudentId() must return the variable studentId.
Notice the naming pattern: a member variable's name is used with "set..." or "get..." to name the setter and getter methods. You will be able to use and recognize this pattern in lots of Java code you read and write for years.
Explanation / Answer
public class Student {
// member variables
private String firstName;
private String lastName;
private String studentId;
// setters and getters
public String getFirstName() {
return firstName;
}
public void setFirstName(String aFirstName) {
firstName = aFirstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String aLastName) {
lastName = aLastName;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String aStudentId) {
studentId = aStudentId;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.