An Example of Inheritance Beaulieu College, 2008
Revisiting the Line class Have a look at the Line class that is listed for you in your textbook on pages 22 and 23. Copy this into Java, or open it if you have it saved. This class drew lines of characters across the screen ################# $$$$$$$$$$$$$$$$$$$$$ ********
Extending the Line class We’re going to make a Shape class that will build on the functions of the line class. We can make shapes by drawing many lines, such as a rectangle: ##########
Extending the Line class Because we already have the capability to draw lines, we don’t have to reprogram this. Let’s get busy with the extending then:
The Shape class public class Shape extends Line { public Shape () super (); } public Shape (int s, char p) super (s, p); public void square () int rows = getSize (); for (int i = 0; i < rows; i ++) draw ();
A Driver program to make Shapes public class UseShapes { public static void main (String [] args) Shape myShape = new Shape (); myShape.setPattern (‘X’); myShape.setSize (5); myShape.square (); myShape.setPattern (‘~’); myShape.setSize (10); myShape.draw (); }
Some points to notice Constructor methods In the Shape class, notice that we declared the constructor methods from the superclass. If you don’t override the constructor methods, you can’t use them in the subclass.
Some points to notice Private properties Driver program In the Line class, the size variable was defined as private. Because of this we had to use the getSize() method to access its value. Driver program Because we’ve extended the Shape class from the Line class, we can use the setSize() and setPattern() methods, that were defined in the Line class.
Some self-study Add a method to the Shape class to draw a triangle: + ++ +++ ++++ +++++