Download
chapter 9 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter 9 PowerPoint Presentation

Chapter 9

100 Vues Download Presentation
Télécharger la présentation

Chapter 9

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Chapter 9 More about Inheritance

  2. Problem • DoME’s print method • It doesn’t print all the information we want. • It only prints the object’s title and comment • The info that is common to the base class

  3. Static Type and Dynamic Type • The static type of an object is what it is declared to be in the code • The dynamic type of an object is what the type is when the program is running • For example: • Item item = (Item)iter.next(); • This may be an item, CD or video when the program is running. • So when we call item.print(), we get the base class’s print method

  4. Method overriding • We can define a method with the same signature in a derived class. • This will override the base class’s method. • Meaning when we call item.print(), if the item is a CD we get the CD’s print method • This is good, but we don’t get any of the information from the superclass’s print method

  5. Dynamic Method Lookup • How exactly does method overloading work? • There is an important concept to know: • Java uses static type checking, but at runtime it uses the method from the dynamic type • This is known as method lookup, method binding or method dispatch. • The bottom line is you need the types to match at compile time, but at runtime the method gets called from the actual type.

  6. Super Calls • To solve this problem, we can call the super class’s print method in the subclass’s print method. public void print() { super.print(); System.out.println(“ ” + artist); System.out.println(“ tracks:” + number of Tracks); }

  7. Super Call Rules • We must explicitly use the key word super • super.method-name ( parameters ); • Super method calls can appear anywhere in the method, not as the first line • There is no automatic call to a super class’s method of the same name

  8. Protected Access • Protected access allows all subclasses direct access to fields and methods declared to be protected. • This level of protection lies in-between public and private. • Only classes in the inheritance heirarchy have direct access to the protect members. • Client classes must use the public interface.