458 Object-Oriented Programming Chapter 9 54 System.exit( 0 (Tomcat web server)

458 Object-Oriented Programming Chapter 9 54 System.exit( 0 ); 55 } 56 57 } // end class InheritanceTest Fig. 9.6Assigning subclass references to superclass references (part 2 of 2). Fig. 9. Line 26 assigns circle1 (a reference to a subclass Circle object) to point2 (a superclass Pointreference). It is always acceptable in Java to assign a subclass reference to a superclass reference, because of the is a relationship of inheritance. A Circleis a Pointbecause class Circleextends class Point. Assigning a superclass reference to a subclass reference is dangerous, as we will see. Lines 28 29 append the result of point2.toString()to output. Interestingly, when point2 is sent the toString message, Java knows that the object really is a Circle, so it chooses the Circle class s toString rather than the Point class s toStringas you might have expected. This is an example of polymorphism and dynamic binding concepts we treat in depth later in this chapter. The compiler looks at the preceding expression and asks the question, Does the data type of the reference point2(i.e., Point) have a toStringmethod with no arguments? The answer to this question is yes (per Point s toString definition on line 41 of Fig. 9.4). The compiler simply checks the syntax of the expression and ensures that the method exists. At execution time, the interpreter asks the question, What type is the object to which point2refers? Every object in Java knows its own data type, so the answer to the question is point2 refers to a Circleobject. Based on this answer, the interpreter calls the toStringmethod of the actual object s data type class Circle s toString method. See the third line of the screen capture to confirm this. The two key programming techniques we used to achieve this polymorphism effect are 1. extending class Pointto create class Circle, and 2. overriding method toStringwith the exact same signature in class Pointand class Circle. Line 33 casts point2, which admittedly is referencing a Circleat this time in the program s execution, to a Circleand assigns the result to circle2(this cast would be dangerous if point2were really referencing a Point, as we will soon discuss). Then we use circle2 to append to output the various facts about circle2. Lines 35 36 Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Leave a Reply