Web host forum - 306 Object-Based Programming Chapter 8 the student object

306 Object-Based Programming Chapter 8 the student object when to calculate the GPA. The client code simply should use the GPA property. The client should not be aware of the underlying implementation. 8.8 Composition: Objects References as Instance Variables ofOther Classes In many situations, referencing existing objects is more convenient than rewriting the objects code for new classes in new projects. Suppose we were to implement an Alarm- Clock object that needs to know when to sound its alarm. Referencing an existing Time object (like those from earlier examples in this chapter) is easier than writing a new Time object. The use of references to objects of preexisting classes as members of new objects is called composition (or aggregation). Software Engineering Observation 8.16 One form of software reuse is composition, in which a class has as members references to objects of other classes. The application of Fig. 8.8, Fig. 8.9 and Fig. 8.10 demonstrates composition. The program contains three classes. Class Date(Fig. 8.8) encapsulates information relating to a specific date. Class Employee(Fig. 8.9) encapsulates the name of the employee and two Date objects representing the Employee s birthday and hire date. Class CompositionTest (Fig. 8.10) creates an object of class Employeeto demonstrate composition. Class Datedeclares intinstance variables month, dayand year(lines 9 11). Lines 16 32 define the constructor, which receives values for month, dayand yearas arguments and assigns these values to the instance variables after ensuring that the values are in a consistent state. Note that lines 25 26 print an error message if the constructor receives an invalid month value. Ordinarily, rather than printing error messages, a constructor would throw an exception. We discuss exceptions in Chapter 11, Exception Handling. Method ToDateString( lines 58 61) returns the string representation of a Date. 1 // Fig. 8.8: Date.cs 2 // Date class definition encapsulates month, day and year. 3 4 using System; 5 6 // Date class definition 7 public class Date 8 { 9 private int month; // 1-12 10 private int day; // 1-31 based on month 11 private int year; // any year 12 13 // constructor confirms proper value for month; 14 // call method CheckDay to confirm proper 15 // value for day 16 public Date( int theMonth, int theDay, int theYear ) 17 { Fig. 8.8 Fig. 8.8Fig. 8.FiFi8g. 8.8g. 8.8Dateclass encapsulates day, month and year information. (Part 1 of 2.)
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

Leave a Reply