|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
(See Dr Okie's examples, too: using Shapes, instead of Animals.)
Digsy the Dog goes "woof, woof".
Caleb the Cat goes "meow, meow".
Python the Python goes "ssss, ssss".
Phydeaux the Dog goes "yip, yip".
How would we represent the above?
Probably with a class Animal, whose fields are ...?
Whose methods are?
But what if we also wanted some methods
and fields specific to certain types of animals —
perhaps Cats have a field "clawSharpness" and
a method "pounce";
perhaps Dogs have a emthod "wagTail" (something that
pythons and cats are actually incapable of?
That's all well and good, but what if we had then and other animals we wanted to model? Say, cats and pythons, which both have ages and sounds, and can getAge and speak … but we will still want separate classes, since some activities are specific to Dogs (perhaps getAgeInDogYears()).
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.
We will add a new class Animal, and put the code which is common to all animals there. Then, we will tell Java that class Cat extends Animal etc..
// 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 mySavings.deposit(12.00), we'd just have called deposit(mySavings, 12.00). With this simple transformation, we could have done everything this semester with static methods (though we'd still need non-static fields). ↩
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.May.01 (Fri) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |