|
home—info—archive—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
We've seen class Dog, where every Dog has a sound, and a method speak (which repeats that sound twice). What if we had other animals we wanted to model? Say, cats and pythons, which both had those same behaviors? However, we will still want separate classes, since some activities are specific to Dogs (like ageInDogYears()).
One solution would be lots of repeated code for speak. But (for the first time)1 we'll see what object-oriented programming buys for us: the ability to share code between different (related) classes.
// Imagine this method in some other class entirely... static String communicateHunger( Animal a ) { return a.speak() + a.speak() + a.speak() + "!"; } |
Constructor: When constructing a Cat, we need to initialize its fields. But wait, isn't that repeated code, found in the superclass constructor? Compare to class Python, to see the proper solution:
super is a keyword to call the superclass constructor. (The complete story on super is below.) This call should be the first line of your constructor (if it isn't there, java rewrites your subclass constructor so that it begins with the line super(). Note that if your superclass didn't have a 0-argument constructor, this will generate an error.)
1Every single method we've written this semester could have been made static! We would just have to make one change to each method: add another parameter -- named this. Then when calling the method, rather than saying jo.setSalary(12.00), we'd just have called setSalary(jo, 12.00). With this simple transformation, we could have done everything this semester without ever needing methods inside of a class (though we'd still need fields inside objects). ↩
home—info—archive—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2008, Ian Barland, Radford University Last modified 2008.Apr.21 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |