Overloading methods and constructors |
Java allows you to have several methods with the same names, but that take different kinds of parameters. A good example is the method name moveTo on graphic objects in the objectdraw library. One version takes a Location, while the other takes two doubles. The Tshirt class we just looked at had only one version of moveTo, one that took two doubles as parameters. However, we could add a second version that takes a location. Typically when we do this, we make the new versions call the original one like the following:
public void moveTo(Location pt) { moveTo(pt.getX(),pt.getY()); }
You can see that this version takes a location pt as parameter and then extracts the x. and y components before calling the original version of moveTo.
There is no real advantage to overloading methods like this, but I wanted to warn you about them in case you saw them in code. Notice that I get exactly the same effect if I use a slightly different name for the method
public void moveToLocn(Location pt) { moveTo(pt.getX(),pt.getY()); }
Grace does not support this kind of overloading, as we would rather change the name a bit as above rather than take the chance of confusing programmers. (There are some complications in how the compiler makes a decision on which version of an overloaded method to call.) We urge you not to use overloading, but be prepared to recognize code that uses it.
Finally, we can also override constructors for a class. For example we could include a second constructor for Tshirt that takes a location and a canvas as parameters rather than two doubles and a canvas. We could simple add the following code after the first constructor body:
public Tshirt (Location pt, DrawingCanvas canvas) { this(pt.getX(), pt.getY(),canvas); }
The body of this constructor uses the keyword this to call the original constructor of the Tshirt class. (I realize that it is confusing that this has two different meanings in Java, but at least they both have to do with accessing things in the same class.) If we wanted to do this in Grace, we would have to work a bit harder, but not too much.
In Grace, we defined:
class tShirt.at (startPosn:Point) size (size':Number) on (canvas:DrawingCanvas) -> MoreDraggable {...}
To get another constructor that uses the same instance variables and methods, but requires different parameters, we could use inheritance:
class tShirt'.atX(x:Number) Y(y:Number) size (size':Number) on (canvas:DrawingCanvas) -> MoreDraggable { inherits tShirt.at(x@y) size (size') on (canvas) }
Because we don't add or override anything from the superclass, we get something with exactly the same instance variables, defs, and methods as the original. Note that we used a slightly different name for the class as Grace will not allow us to write a second class with the same class name as another.
Overloading methods and constructors |