Simple web server - 388 Object-Oriented Programming: Polymorphism Chapter 10 49 50
388 Object-Oriented Programming: Polymorphism Chapter 10 49 50 } // end method Main 51 52 } // end class PointCircleTest Fig. 10.3 Fig. 10.FiFig. 10.3g. 10.3Assigning derived-class references to base-class references. (Part 2 of 2.) Fig. 10.3 Line 21 assigns circle1 (a reference to a derived-class object) to point2 (a base- class reference). In C#, it is acceptable to assign a derived-class object to a base-class reference, because of the inheritance is a relationship. Class Circle inherits from class Point, because a Circleis a Point(in a structural sense, at least). However, assigning a base-class reference to a derived-class reference is potentially dangerous, as we will discuss. Lines 23 24 invoke point2.ToString and append the result to output. When C# encounters a virtual method invocation (such as method ToString), C# determines which version of the method to call from the type of the object on which the method is called, not the type of the reference that refers to the object. In this case, point2refers to a Circleobject, so C# calls Circlemethod ToString, rather than Pointmethod ToString(as one might expect from the point2reference, which was declared as type Point). The decision about which method to call is an example of polymorphism, a concept that we discuss in detail throughout this chapter. Note that if point2 referenced a Point object rather than a Circle object, C# would invoke Point s ToString method. Previous chapters used methods such as Int32.Parse and Double.Parse to convert between various built-in C# types. Now, we convert between object references of programmer-defined types. We use explicit casts to perform these conversions. If the cast is valid, our program can treat a base-class reference as a derived-class reference. If the cast is invalid, C# throws an InvalidCastException, which indicates that the cast operation is not allowed. Exceptions are discussed in detail in Chapter 11, Exception Handling. Common Programming Error 10.1 Assigning a base-class object (or a base-class reference) to a derived-class reference (without an explicit cast) is a syntax error. Software Engineering Observation 10.1 If a derived-class object has been assigned to a reference of one of its direct or indirect base classes, it is acceptable to cast that base-class reference back to a reference of the derived- class type. In fact, this must be done to send that object messages that do not appear in the base class. [Note: We sometimes use the term messages to represent the invocation of methods and the use of object properties.]
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.