Exercises

Classes and Objects

Work on these exercises in the classes-part-one directory in java-web-dev-projects.

Note

If you have not already cloned the java-web-dev-projects project repository you can find it here: Java Web Dev Projects Repository

  1. Open up the file, Student.java, and add all of the necessary getters and setters. Think about the access level each field and method should have, and try reducing the access level of at least one setter to less than public.
public void setName(String name) {
   this.name = name;
}

public void setStudentId(int studentId) {
   this.studentId = studentId;
}

public void setGpa(double gpa) {
   this.gpa = gpa;
}

private void setNumberOfCredits(int numberOfCredits) {
   this.numberOfCredits = numberOfCredits;
}

public String getName() {
   return name;
}

public int getStudentId() {
   return studentId;
}

public int getNumberOfCredits() {
   return numberOfCredits;
}

public double getGpa() {
   return gpa;
}
  1. Instantiate the Student class within the StudentPractice class using yourself as the student. For the numberOfCredits give yourself 1 for this class and a GPA of 4.0 because you are a Java superstar!
Student student = new Student("Your Name", 12345, 1, 4.0);
  1. Within the same package, create a class Course with at least three fields. Before diving into IntelliJ, try using pen and paper to work through what these might be. At least one of your fields should be an ArrayList or HashMap, and you should use your Student class.
public class Course {
   private String topic;
   private Teacher instructor;
   private ArrayList<Student> enrolledStudents;
}
  1. Within the same package, create a class Teacher that has four fields: firstName, lastName, subject, and yearsTeaching. Add getters and setters to the class and add the access level to each field and method in the class. When adding your getters and setters, think about what we read about in the section on Encapsulation.

  2. What access modifier restricts access the most for what we need?

  3. If it is a field, could we restrict the access to private and use getters and setters?

  4. If we do set fields to private, what access level do we have to give our getters and setters?