362 Object-Oriented Programming: (Business web hosting) Inheritance Chapter 9 data, thus

362 Object-Oriented Programming: Inheritance Chapter 9 data, thus leaving the object in an inconsistent state. For example, if we were to declare Circle3 s variable radius as protected, a derived-class object (e.g., Cylinder), could then assign a negative value to radius. The second problem with using protected data is that derived-class methods are more likely to be written to depend on base-class implementation. In practice, derived classes should depend only on the base-class services (i.e., non-private methods and properties) and not on base-class implementation. With protected data in the base class, if the base-class implementation changes, we may need to modify all derived classes of that base class. For example, if for some reason we were to change the names of variables x and y to xCoordinate and yCoordinate, then we would have to do so for all occurrences in which a derived class references these base-class variables directly. In such a case, the software is said to be fragile or brittle. The programmer should be able to change the base-class implementation freely, while still providing the same services to derived classes. (Of course, if the base class services change, we must reimplement our derived classes, but good object-oriented design attempts to prevent this.) Software Engineering Observation 9.5 The most appropriate time to use the protected access modifier is when a base class should provide a service only to its derived classes (i.e., the base class should not provide the service to other clients). Software Engineering Observation 9.6 Declaring base-class instance variables private (as opposed to declaring them protected) enables programmers to change base-class implementation without having to change derived-class implementation. Testing and Debugging Tip 9.1 When possible, avoid including protected data in a base class. Rather, include non- private properties and methods that access private data, ensuring that the object maintains a consistent state. We reexamine our point-circle hierarchy example once more; this time, attempting to use the best software engineering. We use Point3(Fig. 9.12), which declares variables x and yas privateand uses properties in method ToStringto access these values. We show how derived class Circle4 (Fig. 9.13) can invoke non-private base-class methods and properties to manipulate these variables. 1 // Fig. 9.12: Point3.cs 2 // Point3 class represents an x-y coordinate pair. 3 4 using System; 5 6 // Point3 class definition implicitly inherits from Object 7 public class Point3 8 { 9 // point coordinate 10 private int x, y; 11 Fig. 9.12 Fig. 9.12FiFFg. 9.12ig. 9.12ig. 9.12Point3class uses properties to manipulate its privatedata. (Part 1 of 2.)
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

Leave a Reply