Chapter 9 Object-Oriented (Best web hosting site) Programming 457 1 // Fig.
Friday, August 31st, 2007Chapter 9 Object-Oriented Programming 457 1 // Fig. 9.6: InheritanceTest.java 2 // Demonstrating the “is a” relationship 3 4 // Java core packages 5 import java.text.DecimalFormat; 6 7 // Java extension packages 8 import javax.swing.JOptionPane; 9 10 public class InheritanceTest { 11 12 // test classes Point and Circle 13 public static void main( String args[] ) 14 { 15 Point point1, point2; 16 Circle circle1, circle2; 17 18 point1 = new Point( 30, 50 ); 19 circle1 = new Circle( 2.7, 120, 89 ); 20 21 String output = “Point point1: ” + point1.toString() + 22 “nCircle circle1: ” + circle1.toString(); 23 24 // use “is a” relationship to refer to a Circle 25 // with a Point reference 26 point2 = circle1; // assigns Circle to a Point reference 27 28 output += “nnCircle circle1 (via point2 reference): ” + 29 point2.toString(); 30 31 // use downcasting (casting a superclass reference to a 32 // subclass data type) to assign point2 to circle2 33 circle2 = ( Circle ) point2; 34 35 output += “nnCircle circle1 (via circle2): ” + 36 circle2.toString(); 37 38 DecimalFormat precision2 = new DecimalFormat( “0.00″ ); 39 output += “nArea of c (via circle2): ” + 40 precision2.format( circle2.area() ); 41 42 // attempt to refer to Point object with Circle reference 43 if ( point1 instanceof Circle ) { 44 circle2 = ( Circle ) point1; 45 output += “nncast successful”; 46 } 47 else 48 output += “nnpoint1 does not refer to a Circle”; 49 50 JOptionPane.showMessageDialog( null, output, 51 “Demonstrating the “is a” relationship”, 52 JOptionPane.INFORMATION_MESSAGE ); 53 Fig. 9.6Assigning subclass references to superclass references (part 1 of 2). Fig. 9. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01