Classes part 2 - tstorrnetnz/teaching2022 GitHub Wiki

How to think like a computer scientist (HTTLACS)

Otago Workbook L3

Learning Aim: Make your own program that uses classes and arraylists to hold and print out data about a collection of your choice.

In this lesson we create an arraylist and fill it with instances of a class. For example, we can create a class for pens, and fill an arraylist with instances of a pen.

0 1 2 3 4
Pen #1 Pen #2 Pen #3 Pen #4 Pen #5

The repl https://repl.it/@trevorstorr/classes-pens-1 has 2 classes Main and pens. Watch the video https://youtu.be/eOFhkcVgvyI explaining the purpose and organization of the program. In particular, ensure you understand the concept of setter and getter methods for the pen class. The pen objects are held in an arraylist. Therefore the arraylist has elements all of type pen that each contain details of each individual pen.

For you to do:

  • Write a similar program for a topic of your choice that includes a collection e.g. music cars, students in a school, animals in a zoo etc. - Do this in repl. - share it with me. You can use the pens example as a template but you will need to create your own class (car/student etc). Your program should contain an arraylist of objects created from your class (e.g. animals).
  • Make sure your class has class variable, setter and getter methods, just like in the example repl.
  • Print out the details of the objects once they have been stored in the class. Use the getter method to do this.
  • Change the data in one of you classes by using the setter method. Print out the amended (changed) instance of the class to confirm it has in fact changed.

At the moment, whenever we create instances of custom classes, the data for each class - e.g. pen colour etc is manually coded into the program. This is not scalable for bigger programs - we need some way to save and load our data.

One way is to read and write data to a text or comma separated value (CSV) file. We will look at this a bit later - next week perhaps.