80 likes | 226 Views
This chapter delves into the nuances of inheritance in Java, focusing on method overriding, super calls, and access protection. It explains how the `print` method operates in the context of dynamic and static types, highlighting how method invocation is determined at runtime. The chapter covers the importance of using the `super` keyword to access superclass methods and outlines the rules governing super calls. Additionally, it clarifies the protected access modifier, which strikes a balance between public and private access rights for subclasses. Master these concepts to enhance your Java programming skills.
E N D
Chapter 9 More about Inheritance
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
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
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
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.
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); }
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
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.