Exercise Solutions: Classes and ObjectsΒΆ

  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.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    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;
    }
    

    Back to the exercises

  1. In the school 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.

    1
    2
    3
    4
    5
    public class Course {
       private String topic;
       private Teacher instructor;
       private ArrayList<Student> enrolledStudents;
    }
    

    Back to the exercises