Archive for August, 2007

Chapter 9 Object-Oriented (Best web hosting site) Programming 457 1 // Fig.

Friday, August 31st, 2007

Chapter 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

Hosting your own web site - 456 Object-Oriented Programming Chapter 9 the subclass version

Friday, August 31st, 2007

456 Object-Oriented Programming Chapter 9 the subclass version is automatically called. We have actually been overriding methods in every applet in the book. When we extend JAppletto create a new applet class, the new class inherits versions of init and paint (and many other methods). Each time we defined initor paint, we were overriding the original version that was inherited. Also, when we provided method toString for many of the classes in Chapter 8, we were overriding the original version of toString provided by class Object. As we will see in Fig. 9.8, the super reference followed by the dot operator can be used to access the original superclass version of that method from the subclass. Note that class Circle s toString method (lines 44 48) overrides the Point class toStringmethod (lines 41 44 of Fig. 9.4). Class Point s toString method overrides the original toString method provided by class Object. Actually, every class inherits a toString method, because class Object provides the original toString method. This method converts an object of any class into a String representation and is sometimes called implicitly by the program (e.g., when an object is concatenated with a String). Circle method toString directly accesses the protected instance variables x and y that were inherited from class Point. Method toString uses the values of x and y as part of the Circle s String representation. Actually, if you study class Point s toString method and class Circle s toString method, you will notice that Circle s toString uses the same formatting as Point s toString for the Pointparts of the Circle. Also, recall Software Engineering Observation 8.14, indicating that, if a method exists that performs part of another method s task, call the method. Point s toString performs part of the task of Circle s toString. To call Point s toString from class Circle, use the expression super.toString() Software Engineering Observation 9.7 A redefinition of a superclass method in a subclass need not have the same signature as the superclass method. Such a redefinition is not method overriding; rather, it is an example of method overloading. Software Engineering Observation 9.8 Any object can be converted to a String with an explicit or implicit call to the object s toString method. Software Engineering Observation 9.9 Each class should override method toString to return useful information about objects of that class. Common Programming Error 9.4 It is a syntax error if a method in a superclass and a method in its subclass have the same signature but a different return type. The InheritanceTest application (Fig. 9.6) instantiates Point object point1 and Circle object circle1 at lines 18 19 in main. The String representations of each object are assigned to Stringoutputto show that they were initialized correctly (lines 21 22). See the first two lines in the output screen capture to confirm this. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Managed web hosting - Chapter 9 Object-Oriented Programming 455 31 // get

Thursday, August 30th, 2007

Chapter 9 Object-Oriented Programming 455 31 // get radius of Circle 32 public double getRadius() 33 { 34 return radius; 35 } 36 37 // calculate area of Circle 38 public double area() 39 { 40 return Math.PI * radius * radius; 41 } 42 43 // convert the Circle to a String 44 public String toString() 45 { 46 return “Center = ” + “[” + x + “, ” + y + “]” + 47 “; Radius = ” + radius; 48 } 49 50 } // end class Circle Fig. 9.5 Circleclass definition (part 2 of 2). The Circle constructors (lines 8 12 and 15 23) must invoke a Point constructor to initialize the superclass portion of a Circle object (i.e., variables x and y inherited from Point). The default constructor at lines 8 12 does not call a Point constructor explicitly, so Java automatically calls class Point s default constructor (defined at line 8 of Fig. 9.4) that initializes superclass members xand yto zeros. If class Pointcontained only the constructor with arguments (i.e., did not provide a default constructor), a compiler error would occur. Line 19 in the body of the second Circleconstructor explicitly invokes the Point constructor (defined at line 15 of Fig. 9.4) by using the superclass constructor call syntax keyword super followed by a set of parentheses containing the arguments to the superclass constructor. In this case, the arguments are the values xCoordinateand yCoordinatethat are used by the Pointconstructor to initialize the superclass members xand y). The call to the superclass constructor must be the first line in the body of the subclass constructor. To call the superclass default constructor explicitly, use the statement super(); // explicit call to superclass default constructor Common Programming Error 9.2 It is a syntax error if a super call by a subclass to its superclass constructor is not the first statement in the subclass constructor. Common Programming Error 9.3 It is a syntax error if the arguments to a super call by a subclass to its superclass constructor do not match the parameters specified in one of the superclass constructor definitions. A subclass can redefine a superclass method by using the same signature; this is called overriding a superclass method. When that method is mentioned by name in the subclass, Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

454 Object-Oriented Programming Chapter 9 Java automatically attempts (X web hosting)

Wednesday, August 29th, 2007

454 Object-Oriented Programming Chapter 9 Java automatically attempts to call the superclass s default constructor. Note that lines 10 and 17 are comments indicating where the call to the superclass Object s default constructor occurs. Software Engineering Observation 9.6 Every subclass constructor must call one of the direct superclass constructors explicitly or implicitly. Implicit calls can be made only to the no-argument constructor of the superclass. If the superclass does not provide a no-argument constructor, all direct subclasses of that class must call one of superclass s constructors explicitly. Class Circle (Fig. 9.5) inherits from class Point as specified with the extends keyword on line 4. Keyword extendsin the class definition indicates inheritance. All the (nonprivate) members of class Point(except the constructors) are inherited into class Circle. Thus, the public interface to Circle includes the Point class s public methods as well as the two overloaded Circleconstructors and Circlemethods set- Radius, getRadius, area and toString. Notice that method area (lines 38 41) uses predefined constant Math.PI from class Math(package java.lang) to calculate the area of a circle. 1 // Fig. 9.5: Circle.java 2 // Definition of class Circle 3 4 public class Circle extends Point { // inherits from Point 5 protected double radius; 6 7 // no-argument constructor 8 public Circle() 9 { 10 // implicit call to superclass constructor occurs here 11 setRadius( 0 ); 12 } 13 14 // constructor 15 public Circle( double circleRadius, int xCoordinate, 16 int yCoordinate ) 17 { 18 // call superclass constructor to set coordinates 19 super( xCoordinate, yCoordinate ); 20 21 // set radius 22 setRadius( circleRadius ); 23 } 24 25 // set radius of Circle 26 public void setRadius( double circleRadius ) 27 { 28 radius = ( circleRadius >= 0.0 ? circleRadius : 0.0 ); 29 } 30 Fig. 9.5 Circleclass definition (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 9 Object-Oriented Programming 453 1 // Fig. (Geocities web hosting)

Tuesday, August 28th, 2007

Chapter 9 Object-Oriented Programming 453 1 // Fig. 9.4: Point.java 2 // Definition of class Point 3 4 public class Point { 5 protected int x, y; // coordinates of Point 6 7 // No-argument constructor 8 public Point() 9 { 10 // implicit call to superclass constructor occurs here 11 setPoint( 0, 0 ); 12 } 13 14 // constructor 15 public Point( int xCoordinate, int yCoordinate ) 16 { 17 // implicit call to superclass constructor occurs here 18 setPoint( xCoordinate, yCoordinate ); 19 } 20 21 // set x and y coordinates of Point 22 public void setPoint( int xCoordinate, int yCoordinate ) 23 { 24 x = xCoordinate; 25 y = yCoordinate; 26 } 27 28 // get x coordinate 29 public int getX() 30 { 31 return x; 32 } 33 34 // get y coordinate 35 public int getY() 36 { 37 return y; 38 } 39 40 // convert into a String representation 41 public String toString() 42 { 43 return “[” + x + “, ” + y + “]”; 44 } 45 46 } // end class Point Fig. 9.4 Pointclass definition. Class Point s constructors (lines 8 12 and 15 19) must call class Object s constructor. In fact, every subclass constructor is required to call its direct superclass s constructor as its first task, either implicitly or explicitly (the syntax for this call is discussed with class Circlemomentarily). If there is no explicit call to the superclass constructor, Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Http web server - 452 Object-Oriented Programming Chapter 9 9.4 Relationship between

Tuesday, August 28th, 2007

452 Object-Oriented Programming Chapter 9 9.4 Relationship between Superclass Objects and Subclass Objects An object of a subclass can be treated as an object of its superclass. This makes possible some interesting manipulations. For example, despite the fact that objects of a variety of classes derived from a particular superclass might be quite different from one another, we can create an array of references to them as long as we treat them as superclass objects. But the reverse is not true: A superclass object cannot always be treated a subclass object. For example, a Shape is not always a Circle. However, an explicit cast can be used to convert a superclass reference to a subclass reference. This can be done only when the superclass reference is referencing a subclass object; otherwise, Java will indicate a ClassCastException an indication that the cast operation is not allowed. Exceptions are discussed in detail in Chapter 14. Common Programming Error 9.1 Assigning an object of a superclass to a subclass reference (without a cast) is a syntax error. Software Engineering Observation 9.4 If an object has been assigned to a reference of one of its superclasses, it is acceptable to cast that object back to its own type. In fact, this must be done in order to send that object any of its messages that do not appear in that superclass. Our first example consists of two classes. Figure 9.4 shows a Point class definition. Figure 9.5 shows a Circle class definition. We will see that class Circle inherits from class Point. Figure 9.6 shows application class InheritanceTest, which demonstrates assigning subclass references to superclass references and casting superclass references to subclass references. Every applet defined previously has used some of the techniques presented here. We now formalize the inheritance concept. In Chapter 3, we stated that every class definition in Java must extend another class. However, notice in Fig. 9.4 that class Point (line 4) does not use the extends keyword explicitly. If a new class definition does not extend an existing class definition explicitly, Java implicitly uses class Object (package java.lang) as the superclass for the new class definition. Class Object provides a set of methods that can be used with any object of any class. Software Engineering Observation 9.5 Every class in Java implicitly extends Object, unless it is specified otherwise in the first line of the class definition, in which case the class indirectly extends Object. Thus, class Object is the superclass of the entire Java class hierarchy. Let us first examine the Point class definition (Fig. 9.4). The public services of class Point include methods setPoint, getX, getY, toString and two Point constructors. The instance variables x and yof Point are specified as protected. This prevents clients of Point objects from accessing the data directly (unless they are classes in the same package), but enables classes derived from Point to access the inherited instance variables directly. If the data were specified as private, the nonprivate methods of Point would have to be used to access the data, even by subclasses. Note that class Point s toString method overrides the original toString method inherited from class Object. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 9 Object-Oriented Programming 451 Shape TwoDimensionalShape ThreeDimensionalShape (How to cite a web site)

Monday, August 27th, 2007

Chapter 9 Object-Oriented Programming 451 Shape TwoDimensionalShape ThreeDimensionalShape Circle Square Triangle Sphere Cube Tetrahedron Fig. 9.3 A portion of a Shapeclass hierarchy. public class TwoDimensionalShape extends Shape { … } With inheritance, privatemembers of a superclass are not directly accessible from that class s subclasses. Package access members of the superclass are accessible in a subclass only if both the superclass and its subclass are in the same package. All other superclass members become members of the subclass, using their original member access (i.e., public members of the superclass become public members of the subclass, and protectedmembers of the superclass become protectedmembers of the subclass). Software Engineering Observation 9.3 Constructors are never inherited they are specific to the class in which they are defined. It is possible to treat superclass objects and subclass objects similarly; that commonality is expressed in the attributes and behaviors of the superclass. Objects of all classes derived from a common superclass can all be treated as objects of that superclass. We will consider many examples in which we can take advantage of this inheritance relationship with an ease of programming not available in non-object-oriented languages such as C. 9.3 protectedMembers A superclass s public members are accessible anywhere the program has a reference to that superclass type or one of its subclass types. A superclass s private members are accessible only in methods of that superclass. A superclass s protected access members serve as an intermediate level of protection between public and private access. A superclass s protected members may be accessed only by methods of the superclass, by methods of subclasses and by methods of other classes in the same package (protected members have package access). Subclass methods can normally refer to publicand protectedmembers of the superclass simply by using the member names. When a subclass method overrides a superclass method, the superclass method may be accessed from the subclass by preceding the superclass method name with keyword super followed by the dot operator (.). This technique is illustrated several times throughout the chapter. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

450 Object-Oriented Programming (Yahoo free web hosting) Chapter 9 Let us develop

Sunday, August 26th, 2007

450 Object-Oriented Programming Chapter 9 Let us develop a simple inheritance hierarchy. A typical university community has thousands of people who are community members. These people consist of employees, students and alumni. Employees are either faculty members or staff members. Faculty members are either administrators (such as deans and department chairpersons) or teaching faculty. This yields the inheritance hierarchy shown in Fig. 9.2. Note that the inheritance hierarchy could contain many other classes. For example, students can be graduate students or undergraduate students. Undergraduate students can be freshman, sophomores, juniors, and seniors. And so on. The arrows in the hierarchy represent the is a relationship. For example, based on this class hierarchy that we can state, an Employee is a CommunityMember, or a Teacher is a Faculty member. CommunityMember is the direct superclass of Employee, Student and Alumni. CommunityMember is an indirect superclass of all the other classes in the hierarchy diagram. Note that class Employee is both a subclass of CommunityMember and a superclass of Facultyand Staff. Also, starting from the bottom of the diagram, you can follow the arrows and apply the is a relationship all the way up to the topmost superclass in the hierarchy. For example, an Administratoris a Facultymember, is an Employeeand is a CommunityMember. And, in Java, an Administrator also is an Object because all classes in Java have Object as one of their direct or indirect superclasses. Thus, all classes in Java are related in a hierarchical relationship in which they share the 11 methods defined by class Object, which include the toString and finalize methods discussed previously. Other methods of class Objectare discussed as they are needed in the text. Another substantial inheritance hierarchy is the Shape hierarchy of Figure 9.3. There are abundant examples of hierarchies in the real world, but students are not accustomed to categorizing the real world in this manner, so it takes some adjustment in their thinking. Actually, biology students have had some practice with hierarchies. Everything we study in biology is grouped into a hierarchy headed by living things and these can be plants or animals and so on. To specify that class TwoDimensionalShape is derived from (or inherits from) class Shape, class TwoDimensionalShapecould be defined in Java as follows: CommunityMember Employee Student Faculty Staff Administrator Teacher Alumni Fig. 9.2An inheritance hierarchy for university CommunityMembers. g. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 9 Object-Oriented Programming 449 libraries and can

Sunday, August 26th, 2007

Chapter 9 Object-Oriented Programming 449 libraries and can take advantage of other libraries available worldwide. Someday, most software might be constructed from standardized reusable components, just as hardware is often constructed today. This will help meet the challenges of developing the ever more powerful software we will need in the future. 9.2 Superclasses and Subclasses Often an object of one class is an object of another class as well. A rectangle certainly is a quadrilateral (as are squares, parallelograms and trapezoids). Thus, class Rectangle can be said to inherit from class Quadrilateral. In this context, class Quadrilateral is a superclass, and class Rectangle is a subclass. A rectangle is a specific type of quadrilateral, but it is incorrect to claim that a quadrilateral is a rectangle (the quadrilateral could be a parallelogram). Figure 9.1 shows several simple inheritance examples of superclasses and potential subclasses. Inheritance normally produces subclasses with more features than their superclasses, so the terms superclass and subclass can be confusing. There is another way, however, to view these terms that makes perfectly good sense. Because every subclass object is an object of its superclass, and because one superclass can have many subclasses, the set of objects represented by a superclass is normally larger than the set of objects represented by any of that superclass s subclasses. For example, the superclass Vehicle represents in a generic manner all vehicles, such as cars, trucks, boats, bicycles and so on. However, subclass Carrepresents only a small subset of all the Vehicles in the world. Inheritance relationships form tree-like hierarchical structures. A superclass exists in a hierarchical relationship with its subclasses. A class can certainly exist by itself, but it is when a class is used with the mechanism of inheritance that the class becomes either a superclass that supplies attributes and behaviors to other classes or a subclass that inherits those attributes and behaviors. Frequently, one class is both a subclass and a superclass. Superclass Subclasses Student GraduateStudent UndergraduateStudent Shape Circle Triangle Rectangle Loan CarLoan HomeImprovementLoan MortgageLoan Employee FacultyMember StaffMember Account CheckingAccount SavingsAccount Fig. 9.1Some simple inheritance examples in which the subclass is a Fig. superclass. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Web site developers - 448 Object-Oriented Programming Chapter 9 The programmer and

Saturday, August 25th, 2007

448 Object-Oriented Programming Chapter 9 The programmer and designer concentrate on the big picture the commonality among objects in the system rather than the special cases. This process is called abstraction. If a procedural program has many closely related special cases, then it is common to see switch structures or nested if/else structures that distinguish among the special cases and provide the processing logic to deal with each case individually. We will show how to use inheritance and polymorphism to replace such switch logic with much simpler logic. We distinguish between the is a relationship and the has a relationship. Is a is inheritance. In an is a relationship, an object of a subclass type may also be treated as an object of its superclass type. Has a is composition (as we discussed in Chapter 8) . In a has a relationship, a class object has one or more objects of other classes as members. For example, a car has a steering wheel. A subclass s methods might need to access certain of its superclass s instance variables and methods. A crucial aspect of software engineering in Java is that a subclass cannot access the private members of its superclass. If a subclass could access the superclass s private members, this would violate information hiding in the superclass. Software Engineering Observation 9.1 A subclass cannot directly access private members of its superclass. Testing and Debugging Tip 9.1 Hiding private members is a tremendous help in testing, debugging and correctly modifying systems. If a subclass could access its superclass s private members, it would be possible for classes derived from that subclass to access that data as well, and so on. This would propagate access to what is supposed to be private data, and the benefits of information hiding would be lost throughout the class hierarchy. However, a subclass can access the public and protected members of its superclass. A subclass also can use the package access members of its superclass if the subclass and superclass are in the same package. Superclass members that should not be accessible to a subclass via inheritance are declared private in the superclass. A subclass can effect state changes in superclass private members only through public, protected and package access methods provided in the superclass and inherited into the subclass. [Note: We use protectedinstance variables in this chapter to demonstrate how they work. Several of the exercises in this chapter require that you use only private instance variables, to maintain encapsulation.] Software Engineering Observation 9.2 To preserve encapsulation, all instance variables should be declared private and should be accessible only via set and get methods of the class. A problem with inheritance is that a subclass can inherit methods that it does not need or should not have. It is the class designer s responsibility to ensure that the capabilities provided by a class are appropriate for future subclasses. Even when the superclass methods are appropriate for the subclasses, it is common for a sublcass to require the method to perform a task in a manner that is specific to the subclass. In such cases, the superclass method can be overridden (redefined) in the subclass with an appropriate implementation. Perhaps most exciting is the notion that new classes can inherit from abundant class libraries, such as those provided with the Java API. Organizations develop their own class Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01