12.07.2015 Views

COPYRIGHT 2008, PRINCETON UNIVERSITY PRESS

COPYRIGHT 2008, PRINCETON UNIVERSITY PRESS

COPYRIGHT 2008, PRINCETON UNIVERSITY PRESS

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

object-oriented programs: impedance & batons 99more specialized, so it ignores the original method in the Ball class. In computerscience language, we would say that the new getR method overrides the originalmethod.4.9.8 Baton with a Lead Weight (Application)As a second example, we employ inheritance to create a class of objects representinga baton with a weight at its center. We call this new class LeadBaton.java and makeit a child of the parent class Baton.java. Consequently, the LeadBaton class inheritsall the methods from the parent Baton class, in addition to having new ones ofits own:✞☎/ / LeadBaton : class inheritance of methods from Baton✝public class LeadBaton {public double M; / / Non−static class variablesLeadBaton ( Path p, Ball b, double L1 , double w1, double M1) {super (p, b, L1, w1) ; / / Baton constructorM=M1;}public double getM ( ){ return super . getM ( ) + M; } // Call getM in BatonHere the nondefault constructor LeadBaton(. . .) takes five arguments, while theBaton constructor takes only three. For the LeadBaton constructor to work, it mustcall the Baton constructor in order to inherit the properties of a Baton. This is accomplishedby use of the key word super, which is shorthand for look in the superclassand which tells Java to look in the parent, or superclass, for the constructor. Wemay also call methods with the super key word; to illustrate, super.getM() will callthe getM method from Baton in place of the getM method from LeadBaton. Finally,because the LeadBaton class assigns new values to the mass, LeadBaton overridesthe getM method of Baton.Exercise:1. Run and create plots from the LeadBaton class. Start by removing the mainmethod from Baton.java and placing it in the file Main.java. Instead ofcreating a Baton, now create a LeadBaton withLeadBaton myBaton = new LeadBaton(myPath, myBall, 2.5, 15., 10.);Here the argument “10.” describes a 10-kg mass at the center of the baton.2. Compile and run the main method, remembering to use the option“−classpath.” if needed. You should get a plot of the energies of the leadbaton versus time. Compare its energy to an ordinary baton’s and commenton the differences.−101<strong>COPYRIGHT</strong> <strong>2008</strong>, PRINCET O N UNIVE R S I T Y P R E S SEVALUATION COPY ONLY. NOT FOR USE IN COURSES.ALLpup_06.04 — <strong>2008</strong>/2/15 — Page 99

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!