Spaces:
Running
Running
| Write a category 'Gradebook' with the following properties | |
| Attribute owner of type string | |
| Attribute grades, whose type is a list. The list must be able to store objects of type Grade (the class can be found in the attached program) | |
| A constructor that takes the owner as a parameter and sets the value of the attribute. The constructor also initializes the grade list. | |
| The attributes must be 'protected' so that the client cannot see them, but any inheriting classes can. | |
| import java.util.Random; | |
| import java.lang.reflect.Field; | |
| import java.util.ArrayList; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random r = new Random(); | |
| System.out.println("Testing class Gradebook..."); | |
| Gradebook gb = new Gradebook("Gary Grader"); | |
| System.out.println("Object created!"); | |
| try { | |
| Field number = gb.getClass().getDeclaredField("owner"); | |
| boolean numberPrivate = number.getModifiers() == 4; | |
| System.out.println("Owner is protected: " + numberPrivate); | |
| } catch (Exception e) { | |
| System.out.println("Attribute owner is not defined"); | |
| } | |
| try { | |
| Field grades = gb.getClass().getDeclaredField("grades"); | |
| boolean asPrivate = grades.getModifiers() == 4; | |
| System.out.println("Grades is protected: " + asPrivate); | |
| ArrayList<Grade> as = gb.grades; | |
| boolean isInitialized = gb != null; | |
| System.out.println("Grades is initialized: " + isInitialized); | |
| } catch (Exception e) { | |
| System.out.println("Attribute grades is not initialized"); | |
| } | |
| } | |
| } | |
| class Grade { | |
| private String student; | |
| private int grade; | |
| public Grade(String student, int grade) { | |
| this.student = student; | |
| this.grade = grade; | |
| } | |
| public String getStudent() { | |
| return student; | |
| } | |
| public int getGrade() { | |
| return grade; | |
| } | |
| } | |
| //add | |
| class Gradebook { | |
| protected String owner; | |
| protected ArrayList<Grade> grades; | |
| // constructor | |
| public Gradebook(String owner) { | |
| this.owner = owner; | |
| this.grades = new ArrayList<Grade>(); | |
| } | |
| } | |
| Testing class Gradebook... | |
| Object created! | |
| Owner is protected: true | |
| Grades is protected: true | |
| Grades is initialized: true | |