ICS 4U Classes and Inheritance - University of ??ICS 4U Introduction to Programming in Java Chapter 10 Notes Classes and Inheritance In Java all programs are classes, but not all classes are programs

Download ICS 4U Classes and Inheritance - University of  ??ICS 4U Introduction to Programming in Java Chapter 10 Notes Classes and Inheritance In Java all programs are classes, but not all classes are programs

Post on 03-Apr-2018

216 views

Category:

Documents

4 download

Embed Size (px)

TRANSCRIPT

  • ICS 4U

    Introduction to Programming in Java

    Chapter 10 Notes Classes and Inheritance In Java all programs are classes, but not all classes are programs. A standalone application is a class that contains a main method, and may, or may not, contain other methods. An applet is a class that extends the class Applet. It contains a number of standard methods including a paint method. Neither one of these two classes is used as a template to create objects. In this chapter we look at the more general idea of a class, how objects are instantiated from it and how new classes can be produced from it by inheritance. 10.1 Objects and Abstract Data Types

    As programs become larger, controlling interference between parts becomes more difficult. Interference can be minimized by isolating all methods that share common variables and encapsulating them in an object, along with the shared variables. When this is done, no other part of a program needs to be concerned with how the data is stored in the object. Only those methods inside the object are involved. In this sense the data is abstracted and we speak of the whole as an abstract data type or ADT. Of course, one object in a program must communicate with other objects or it would not be a single program, just a group of separate, smaller programs. This communication occurs when one object uses methods of another object. This is known as message passing. For any object to use a method encapsulated in another object, several things are necessary. The object using another objects method must have imported the other class to which the other object belongs either explicitly or implicitly. The method that is used must have been declared public. In Java, objects are instantiated from classes which act as templates for their creation. Whenever changes are made in the way an object stores data or the way that its methods are implemented, assuming their signatures and what they accomplish remain unchanged, other objects using objects instantiated from the class need not be altered. By this means, unwanted interference between objects in a larger program can be prevented, without having to keep each class unchanged.

    10.2 Using a Class We will begin by looking at an object instantiated from a class from the outside, as any other object or main method using it would, and see how it can be used. For example, consider a class called Turtle that can be used to instantiate objects to produce line drawings. To visualize the object, think of a turtle that is set at a certain position on the screen and pointed in a certain direction. As the turtle moves, it traces a line on the screen. It always moves in a straight

  • line unless its direction is changed. It can turn a certain angle to its left or to its right. It can also move without leaving a trace. Here is the list of the public methods of the Turtle class with their signatures. These angles are in degrees and measured in a counterclockwise direction from a horizontal line pointing right, just as they are in mathematics. Signature Behariour setColor(Color clr) Set colour of trace. setPosition(int x, int y) Place turtle at (x,y). setAngle(int angle) Point turtle at angle to horizontal. move(int distance) Move distance in pointing direction. turnLeft(int angle) Turn angle to turtles left from present pointing

    direction. turnRight(int angle) Turn angle to turtles right from present pointing

    direction. showTrace() Cause trace to show. hideTrace() Stop trace from showing.

    Sample Turtle Classes (NOTE: import hsa.book.*; contains the Turtle class) // The "RedSquare" class. // Draw a red square of size 30 pixels with its upper-left corner // at the center of console window. // Instantiate object t and set color. import java.awt.*; import hsa.Console; import hsa.book.*; public class RedSquare { static Console c; // The output console public static void main (String [] args) { c = new Console (); Turtle t; t = new Turtle (c); t.setColor (Color.red); t.move (30); // Draw first side. t.turnRight (90); t.move (30); // Draw second side. t.turnRight (90); t.move (30); // Draw third side. t.turnRight (90); t.move (30); // Draw fourth side. } // main method } // RedSquare class or

  • public static void main (String [] args) { c = new Console (); Turtle t; t = new Turtle (c); t.setColor (Color.red); // uses a loop to make the square for (int side = 1 ; side

  • Here is a main method that uses two turtles to draw two spirals, one in orange and the other in cyan. Each spiral begins at the center of the screen but the orange turns to the right, and the cyan to the left. // The "DrawMoon" class. // Draws a moon at center of console window // of radius 60 pixels and color green. import java.awt.*; import hsa.Console; import hsa.book.*; public class DrawMoon { static Console c; // The output console public static void main (String [] args) { c = new Console (); Turtle t; t = new Turtle (c); t.setColor (Color.green); for (int square = 1 ; square

  • Chapter 10 Notes continued 10.5 Method Overloading

    In the Turtle class definition there are two methods named Turtle. These are each constructor methods. When a turtle object is instantiated using the constructor with one parameter, as by Turtle(Console c), the first version is used. The turtle is set to the default position of the center of the screen, pointing to the right. The second version has, as well, parameters for the coordinates of the starting position and starting angle. This allows the user to begin drawing at another point in the window and pointing in another direction. In either case the turtle is set to showing the trace and drawing in black. In the second version of the constructor there must be a distinction between the parameters of the constructor x and y, and angle and the class variables x, y, and angle. To differentiate them, the keyword this identifies the variables that belong to the object itself. Thus the statement this.x = x; assigns to the instance variable x the value of the parameter x. When two or more methods have the same identifier, as the two versions of the constructor method Turtle have here, we say the method is overloaded. Which version is to be used depends on the parameters provided. It is possible to have methods of a class other than the constructor method overloaded but this is not done. Many classes in the Java library provide a variety of constructor methods. No two of these can have the same number and data type of parameters of they could not be distinguished from one another. If no constructor method is provided for a class, the initial values of instance variables are automatically default values.

    10.6 Creating a New Class by Inheritance It is possible to create a new class based on an old one by modifying it in various ways. New methods can be added or existing methods changed. We will change the class Turtle by allowing control of the width of the line that is traced by the turtle. This means we must add an additional class variable called lineWidth that can be changed from its default value of 1 pixel by the operation setLineWidth (int width) where width is the new line width. We must also change the existing method move to draw a line of the proper width. It, in turn, will use a new method that is added, but not made public, called drawFatLine. This method creates a fat line by drawing a ball of radius half the line width points along the line, close enough together to create the effect of a solid line, somewhat like a ballpoint pen. Here is the new class.

  • // The "FatTurtle" class. // For drawing graphics with a variety of line widths. // This class extends the Turtle class. import hsa.Console; import hsa.book.*; public class FatTurtle extends Turtle { // Add a new variable. protected int lineWidth; // Only one version of constructor provided. public FatTurtle (Console c) { super (c); // Use default setting for other variables defined in Turtle class. lineWidth = 1; } // FatTurtle constructor // Add a new method to set LineWidth. public void setLineWidth (int newWidth) { lineWidth = newWidth; } // setLineWidth method // Draw a filled ball of radius and center at (x, y) // in the current color. protected void drawBall (int xc, int yc, int radius) { int diameter = radius * 2; int x = xc - radius; int y = yc - radius; c.fillOval (x, y, diameter, diameter); } // drawBall method // Add method drawFatLine. protected void drawFatLine (int x1, int y1, int x2, int y2) { // Line drawn by moving a ball point pen whose ball // is half line width. // Line drawn at x values of ball separated by DX which // is half the radius. // Constants used in calculation. final double LEN = Math.sqrt (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); final double SINA = (y2 - y1) / LEN; final double COSA = (x2 - x1) / LEN; final int RADIUS = (lineWidth / 2) + 1; final double DX = RADIUS * COSA / 2; final double DY = RADIUS * SINA / 2; // Set position to draw first ball's center at (x1, y1). double xpos = x1; double ypos = y1; // Draw series of balls along line from (x1, y1) to (x2, y2). do

  • { drawBall ((int) Math.round (xpos), (int) Math.round (ypos), RADIUS); xpos += DX; ypos += DY; } while (Math.sqrt ((x2 - xpos) * (x2 - xpos) + (y2 - ypos) * (y2 - ypos)) >= RADIUS / 2); } // drawFatLine method // This method overrides the move method of the Turtle class. public void move (int distance) { double rAngle = angle * Math.PI / 180; final int newx = (int) Math.round (x + Math.cos (rAngle) * distance); final int newy = (int) Math.round (y + Math.sin (rAngle) * distance); if (showing) { c.setColor (clr); if (lineWidth == 1) c.drawLine (x, y, newx, newy); else drawFatLine (x, y, newx, newy); } x = newx; y = newy; } // move method } /* FatTurtle class */ Notice that it is not necessary to repeat the methods of Turtle that are unchanged. The only new variable added is lineWidth. The new method made public is setLineWidth. The new method move overrides (replaces) the old version of move. If the width is given as 1 pixel, the Console method drawLine is used. If the width has been set at another value then the new method drawFatLine is used. Using the Modified Class Here is a main method that uses the FatTurtle class to draw concentric fat circles with centers at the center of the window. The circles will each be made up of 36 short straight lines. A yellow circle will have a radius of getWidth/6 and lineWidth of 10 and a green circle radius getWidth/4 and lineWidth of 20 pixels. // The "FatCircles" class. // Use FatTurtle class to draw concentric circles. import java.awt.*; import hsa.Console; public class FatCircles { static Console c; // The output console public static void main (String [] args) { c = new Console (); FatTurtle turtle1, turtle2;

  • turtle1 = new FatTurtle (c); turtle2 = new FatTurtle (c); turtle1.setLineWidth (10); turtle2.setLineWidth (20); turtle1.setColor (Color.yellow); turtle2.setColor (Color.green); // Set the x position of each turtle at its own radius from the center // of the window pointing up. // Compute some constants. final int XC = c.getWidth () / 2; final int YC = c.getHeight () / 2; final int RADIUS1 = c.getWidth () / 6; final int RADIUS2 = c.getWidth () / 4; final int STEPANGLE = 10; final double STEPANGLERADIANS = STEPANGLE * 2 * Math.PI / 360; final int DISTANCE1 = (int) Math.round (RADIUS1 * STEPANGLERADIANS); final int DISTANCE2 = (int) Math.round (RADIUS2 * STEPANGLERADIANS); turtle1.setPosition (XC + RADIUS1, YC - DISTANCE1 / 2); turtle2.setPosition (XC + RADIUS2, YC - DISTANCE2 / 2); turtle1.turnLeft (90); turtle2.turnLeft (90); for (int direction = 0 ; direction

Recommended

View more >