453.chap53.Structure 5 - Objects II

Embed Size (px)

Citation preview

  • 8/7/2019 453.chap53.Structure 5 - Objects II

    1/8

    453

    Structure 5: Objects IIThis unit extends the discussion of object-oriented programming and introduces splittinga program into multiple les.

    Syntax introduced:extends, super

    There is far more to object-oriented programming than was described in Structure 4(p. 395). As your programs become longer and your ideas grow more ambitious, theadditional object-oriented programming concepts and techniques discussed in this unitbecome important for managing code.

    Multiple constructors

    A class can have multiple constructors that assign the elds in different ways. Sometimesits benecial to specify every aspect of an objects data by assigning parameters to theelds, but other times it might be appropriate to dene only one or a few.

    In the next example, one constructor sets the x-coordinate, y-coordinate, and radius,while the other uses preset values. When the object is created, the program chooses theconstructor to use depending on the number and type of variables specied. At the endof setup() , the sp1 object is created using the rst version of the Spot constructor, andthe sp2 object is created using the second version.

    Spot sp1, sp2;

    void setup() {size(100, 100);smooth();noLoop();// Run the constructore without parameterssp1 = new Spot();// Run the constructor with three parameterssp2 = new Spot(66, 50, 20);

    }

    void draw() {sp1.display();sp2.display();

    }

    48-01

  • 8/7/2019 453.chap53.Structure 5 - Objects II

    2/8

    454 Structure 5: Objects II

    class Spot {float x, y, radius;

    // First version of the Spot constructor,// the fields are assigned default values

    Spot() {x = 33;y = 50;radius = 8;

    }

    // Second version of the Spot constructor,// the fields are assigned with parametersSpot(float xpos, float ypos, float r) {

    x = xpos;y = ypos;radius = r;

    }

    void display() {ellipse(x, y, radius*2, radius*2);

    }}

    Composite objects

    An object can include several other objects. Creating such composite objects is a goodway to use the principles of modularity and build higher levels of abstraction. In thenatural world, objects often possess components that operate independently but inrelation to other components. Using a biological analogy, you might create a cell class,groups of which can be combined into muscle tissue and nervous tissue. These tissuescan be combined into organs, and the organs into an organism. With multiple layersof abstraction, each step is built from composites of the previous layer. A bicycle classprovides a different sort of example. It could be composed of objects for its frame,wheels, brakes, drivetrain, etc., and each of these units could be built from other classes.For example, the drivetrain could be built from objects for the pedals, crankset, and

    gears.The following program combines the Egg class (p. 405) and the Ring class (p. 408)

    to create a new class called EggRing . It has one Egg object called ovoid , created in theconstructor, and one Ring object called circle , created at the base of the class. Thetransmit() method calls the methods for both classes and resets circle when theobject reaches its maximum size. As in all the examples using classes, the referencedclasses have to be included in the sketch for the project to run.

    48-01cont.

  • 8/7/2019 453.chap53.Structure 5 - Objects II

    3/8

    455 Structure 5: Objects II

    // Requires Egg and Ring classes (codes 43-08 and 43-11)

    class EggRing {Egg ovoid;Ring circle = new Ring();

    EggRing(int x, int y, float t, float sp) {ovoid = new Egg(x, y, t, sp);circle.start(x, y - sp/2);

    }

    void transmit() {ovoid.wobble();ovoid.display();circle.grow();circle.display();if (circle.on == false) {

    circle.on = true;}

    }}

    When the EggRing class is used in a program, each instance draws an egg to the screenwith one Ring object growing from its center.

    // Requires the Egg, Ring, and EggRing classes

    EggRing er1, er2;

    void setup() {size(100, 100);smooth();er1 = new EggRing(33, 66, 0.1, 33);er2 = new EggRing(66, 90, 0.05, 66);

    }

    void draw() {

    background(0);er1.transmit();er2.transmit();

    }

    48-02

    48-03

  • 8/7/2019 453.chap53.Structure 5 - Objects II

    4/8

    456 Structure 5: Objects II

    Inheritance

    A class can be dened using another class as a foundation. In object-orientedprogramming terminology, one class can inherit elds and methods from another. Anobject that inherits from another is called a subclass , and the object it inherits from iscalled a superclass . A subclass extends the superclass. When one class extends another,all of the methods and elds from the superclass are automatically included in thesubclass. New elds and methods can be added to the subclass to build on the data andbehavior of its superclass. If a method name is repeated within the subclass and has thesame prototype (the same number of parameters with the same data types) as the onein the superclass, the method in the subclass overrides the other, thereby replacing it.When a method or eld from the superclass is called from within the subclass, the nameis prefaced with the keyword super to let the software know this method or eld is apart of the superclass. The following examples clarify these new terms and concepts.

    The Spin class was created to help explain the concept of inheritance. This veryminimal class has elds for setting the x-coordinate, y-coordinate, speed, and angle. Ithas one method to update the angle.

    class Spin {float x, y, speed;float angle = 0.0;

    Spin(float xpos, float ypos, float s) {x = xpos;y = ypos;speed = s;

    }

    void update() {angle += speed;

    }}

    The SpinArm class inherits elements from Spin and draws a line using the superclasssdata. The constructor for SpinArm simply calls the constructor of the superclass. Thedisplay() function uses the inherited x, y , angle , and speed elds to draw a rotatingline. Notice that the declarations for these elds are not repeated in the subclass becausethey are accessible to the subclass.

    In the SpinArm constructor, super() is used to call the constructor of the Spinsuperclass. If super() with parameters is not used in the constructor of a subclass, a linecalling super() with no parameters will be inserted behind the scenes. For this reason,any class meant to be extended will usually require a version of its constructor with noparameters, except in cases like this example where all subclasses call super() explicitly.

    48-04

  • 8/7/2019 453.chap53.Structure 5 - Objects II

    5/8

    457 Structure 5: Objects II

    class SpinArm extends Spin {

    SpinArm(float x, float y, float s) {super(x, y, s);

    }

    void display() {strokeWeight(1);stroke(0);pushMatrix();translate(x, y);angle += speed;rotate(angle);line(0, 0, 100, 0);popMatrix();

    }}

    The SpinSpots class also inherits the elements of Spin . Like the SpinArm class, ituses its superclasss elds and constructor, but it builds even further on Spin by addinganother eld. The dim eld was added to give the option to change the size of the circles.Notice that this eld is declared at the top of the class, assigned in the constructor, andaccessed in the display() method to set the size of the circles.

    class SpinSpots extends Spin {float dim;

    SpinSpots(float x, float y, float s, float d) {super(x, y, s);dim = d;

    }

    void display() {noStroke();pushMatrix();translate(x, y);angle += speed;

    rotate(angle);ellipse(-dim/2, 0, dim, dim);ellipse(dim/2, 0, dim, dim);popMatrix();

    }}

    48-05

    48-06

  • 8/7/2019 453.chap53.Structure 5 - Objects II

    6/8

  • 8/7/2019 453.chap53.Structure 5 - Objects II

    7/8

    459 Structure 5: Objects II

    super.press();xoff = mx - x;yoff = my - y;

    }

    void drag(int mx, int my) {if (press == true) {

    x = mx - xoff;y = my - yoff;

    }}

    }

    The following example shows this new DragButton class embedded into a program.Its methods are run from the mouse event functions to register the status of the mousewith the icon object.

    // Requires DragButton and Button classes

    DragButton icon;

    void setup() {size(100, 100);smooth();color gray = color(204);color white = color(255);color black = color(0);

    icon = new DragButton(21, 42, 50, gray, white, black);}

    void draw() {background(204);icon.update(mouseX, mouseY);icon.display();

    }

    void mousePressed() { icon.press(mouseX, mouseY); }

    void mouseReleased() { icon.release(); }void mouseDragged() { icon.drag(mouseX, mouseY); }

    The DragButton class can be extended further to allow an image to be loaded anddisplayed as the icon. This class is very similar to DragButton but adds a eld for theimage and completely overrides the display() method to draw an outline around theimage. This action provides visual feedback when the cursor is over the icon and when

    48-08cont.

    48-09

  • 8/7/2019 453.chap53.Structure 5 - Objects II

    8/8

    460 Structure 5: Objects II

    the mouse is over the icon and pressed. Try integrating this new DragImage class intothe previous example.

    class DragImage extends DragButton {PImage img;

    DragImage(int x, int y, int d, String s) {super(x, y, d, color(204), color(255), color(0));img = loadImage(s);

    }

    // Override the display() from Buttonvoid display() {

    if (press == true) {stroke(pressGray);

    } else if (over == true) {stroke(overGray);

    } else {stroke(baseGray);

    }noFill();rect(x-1, y-1, size+1, size+1);image(img, x, y, size, size);

    }}

    While modular programming is an important technique, it can be too much of a good

    thing. Be careful to not abstract your code to a point where it becomes cumbersome. Inthe example above, the description of this simple button behavior with three classesis not practical. It was created this way to demonstrate key concepts of object-orientedprogramming, but could (and probably should) be simplied to one or two classes.

    Exercises1. Write another constructor for the Spot class and use it within a variation

    of code 48-01.2. Create your own composite class from two previously existing classes.

    3. Create a unique subclass from the Button class.

    48-10