/** * The purpose of this file is to illustrate some additional concepts * about objects and classes. This is not a correct commenting style * and should not be duplicated in any real programs you write. * * Concepts * 1) What is a "calling object" ? * 2) How do you pass in a parameter of the class type? * 3) How do you return a value of the class type? */ class Weight { private int pounds; private int ounces; /* * This is the constructor. It is called anytime someone * does a "new Weight(p,o)" in their program. The p and * the o are the actual parameters (in their program) * which get assigned to pds and ozs here in our method. */ public Weight ( int pds, int ozs ) { pounds = pds; ounces = ozs; } /* * Here a variable of type Weight has called the "print" method. * This is the calling object (that variable). We have * access to that variable's pounds and ounces private * instance variables here and thus can use them to print * the message. */ public void print ( ) { System.out.println(pounds + " lbs, " + ounces + " oz."); } /* * This one is tricky. There are THREE different objects of type * Weight to keep track of. * 1) The calling object. In the example WeightTester.java program * w1 is the calling object. Again we have access to w1's private * data which is refered to as pounds and ounces. * 2) The parameter. w is a parameter here. In our WeightTester.java * program, w is the w2 parameter passed to us. We have access to w2's * private data (which in this method is refered to as w's data). We must * use w.pounds and w.ounces in this method so that the compiler knows * we are talking about w's private data and not the calling object's * data. * 3) The return value. Notice this method returns an object of * type Weight. In some instances we may return the parameter or * the calling object. But most often, as is shown here, we create * a different object that does not yet exist and then return this * object. Once we add the weight for the calling object and the * parameter (w1 and w2 in our WeightTester.java program), we can * create a new Weight object. We use the variable "retValue" to * hold this newly created object. Then we can return this object * once it is created. Notice that we invoke the constructor for this * new object from within this method. */ public Weight add ( Weight w ) { int newPounds = pounds + w.pounds; int newOunces = ounces + w.ounces; Weight retValue = new Weight(newPounds, newOunces); return retValue; } /* As an additional note, I have not necessarily computed the return weight * correctly above. I did this on purpose because I don't want to give * away the "difference" method that you must implement for Assignment 10. * You might think about why the above computation does not produce the * correct value for every addition and what you might do to fix it. */ }