Prerequisite Knowledge
This lab assumes that you have the knowledge to properly write methods and use control statements, as well as the knowledge to control the Turtle's movements.
A class can be related to another class by inheritance. This means that it has all the instance variables and methods that its "parent" class does, but it may extend its parent by adding additional methods or modifying their behavior. These additional methods and behaviors are accessible by a "child" object, but not by a "parent" object.
Here we can see that the syntax for defining a class that inherits or extends another is straightforward:
class Parent {
// definitions
}
class Child extends Parent {
// definitions
}
So here, if we were to code our Parent class with just a method that would send our Turtle driving forward, and our Child class with just a method that would stop our Turtle, then we would be able to tell our Child to both go forward, and stop. Our parent however, would not have the capability to stop. This lab assumes that you have the knowledge to properly write methods and use control statements, as well as the knowledge to control the Turtle's movements.
Using task1.java (you'll recognize this from the lab on building classes), rewrite the Note class so that it is a child of a new class called MusicThing. Next, create another class called Rest, that also extends MusicThing. This can be done by simple copying, pasting, and editing the Note class. From there you need to:
Now, revise your code from Task 1 so that the code in common between the Note class and the Rest class is moved into the MusicThing class. Since both of these classes extend the MusicThing class, they will both inherit all of the methods and variables declared in MusicThing, thus there is no need to have the same methods declared twice when they can be declared once. By moving all of the common code into the MusicThing class, our 'child' class now actually inherits something.
In the past two tasks, we modified a file to allow for inheritance. With this task, we are going to work from the ground up to build a program that uses inheritance. You need to write a program in which:
In this lab, you learned the following: