This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: COMP 250 Winter 2010 30 - inheritance 2 March 26, 2010 Example (of inheritance) See the example from the slides in which we consider a method threaten() in the Dog() class. This method calls showTeeth() , which is defined in the Dog class only, and bark() which is defined in both the Dog and subclasses of Dog , in particular, Doberman . Consider what happens when a Doberman object invokes the method threaten() . Which version of bark() is used? To reason about this, you must understand that the method bark() in the Dog() class is invoked without specifying which object is invoking it. In the code, there is an implicit this object filled in. So you should replace bark() with this.bark() and once you do that you will see that if the caller is a Doberman object, then the bark() that is used is the bark() defined for the Doberman class. If you wanted a Doberman object to bark like a Dog , you could do this by explicitly writing super.bark() . The Doberman object would then go to its superclass which is Dog and use the bark() method from the Dog class. Constructors and super When an object of a subclass is instantiated (using one of the class’es constructor methods), the fields of the object are created. This includes the fields of the superclass 1 and the fields of the superclass’es superclass, etc. This is called constructor chaining . How is it achieved ? The first line of any constructor is super(...); // possibly with parameters and if you leave this line out (as you have done in the past) then the Java compiler puts in the following (with no parameters):...
View Full Document