Inheritance is an important element of OOP programming. Using Carol Lewis’ Inheritance workshop we will re-create her example of an array of Dogs. This array will be a mixed array because some of the elements will be of the class “Dogs” while others will be of the class “Working Dogs”; Working Dogs inherits from the Dog class – it is a sub-class of Dogs.

Our first effort must be to create a Bare Bones program that runs. It will have a text file, a UI class, a Manager Class, a Dog class, and a Working Dog class (a subclass to Dog)

NOTE: Our Bare Bones text file will not have any working dogs at this point. We get our program to run first with the easiest solution before we attempt the more complicated element of the sub-class.

EXAM TIP for learners who find this challenging. Make a duplicate copy of the text file and remove the lines that will become child objects. Code your answer until your program runs with the parent class only. Then swop back to the original text file as provided and code the child objects.

Click here.

We can now expand our Manager class to read in the text file and instantiate an array of dogs.

Click here

Now it is time to add Working Dogs to the text file. In our DogManager class we edit its constructor method to instantiated Dogs objects and Working Dog objects. We are able to do this because Working Dogs have a trainer while regular Dogs do not; therefore the text file has an extra field.

Click here

Finish off, and clean up your object classes (Dog and Working Dog). We can ask NetBeans to create our getters and setters for us. Select the object class, right click in the class, “Insert code”, “getter and setters”, select the fields you want and the methods will be inserted into your code for you. (Note that the getter for boolean is slightly different.) Ensure that the object’s properties have been flagged as private. Cut and paste your methods into logical order, correct indentation and add a few comments.

Click here

Now it is time to add more methods to the manager class i.e. sort by the dog’s name and sort by the dog’s age. For more information about the bubble sort see Bubble Sort 1, 2 and 3 in java-teacher.

Click here