Lab 14 – Inheritance and Sorting

Write a class named Student that models a college student. The Student class should include fields for the student’s first name (String), last name (String), student id (int) and major (String) along with an access methods (getters) for the fields. The class should set all of its fields in the constructor using arguments passed to the constructor.  If any of the Strings are null or the empty string or if the integer is less than or equal to 0, the constructor should throw an IllegalArgumentException.  Note which class the IllegalArgumentException class extends.

Write a class named TransferStudent that is a subclass of Student.  The class has a field that specifies the number of credits transferred in to the college (int). The constructor should set all of the class fields (and super class fields) using the values of the arguments passed into the constructor.  If the number of credits transferred in is less than 0 then the constructor should throw an IllegalArgumentException.  The class should have access methods (getters) to get the values stored in the fields but should not contain setters. Override toString() to return a String containing the data in all of the class’ and superclass’ fields, each separated by colons (:).

Write a driver (a runnable program) in a class named Lab14. The class should have three methods: sortStudents, writeStudents, and main.

The sortStudents method should take an array of Students as an argument.  The method sorts the elements in the array using the Bubble-Sort algorithm discussed in lecture so that the elements in the array are sorted in-place according to their student ids (in increasing order).

In your driver, add a method named writeStudents that has two arguments. The first argument is a file name (String) and the second argument is an array of TransferStudent objects. The function writes the first name, last name, student id, major and number of credits transferring in of each element in the array to the file named in the first argument. The file should contain one line for each object in the array with each field separated by colons.

The main method should create two objects of type TransferStudent using the following data and inserts their references into an array of TransferStudents.

    • Kim Brown is a Computer Science major with 27 credits transferring in.  Her student id is 67890.
    • John Doe is a Computer Science major with 24 credits transferring in.  His student id is 12345.

The main should then sort the elements in the array by calling sortStudents.

Finally, the main method should call the writeStudents method using the file name “students.txt” and the array of TransferStudents.


Compile, test, debug, and push to Github when complete.

© 2024, Eric. All rights reserved.