110 of 208
ZBasic Language Reference 102 ZX Microcontroller Family relationships between values of multiple data members. Such control would be difficult or impossible to enforce if outside entities were allowed to directly modify the data members. Moreover, requiring the use of mutator methods to change data members also allows the freedom to later change the way that the data members are stored without affecting any of the object’s users. An example of enforcing data value ranges is shown below in the re-written SetTime() method. The class definition has also been augmented with accessor methods for the three data members. Class MyTime Private hour as Byte Private minute as Byte Private seconds as Single Public Sub SetTime(ByVal h as Byte, ByVal m as Byte, ByVal s as Single) hour = Min(h, 23) minute = Min(m, 59) Seconds = Min(s, 59.999) End Sub Public Function GetHour() as Byte GetHour = hour End Function Public Function GetMinute() as Byte GetMinute = minute End Function Public Function GetSeconds() as Single GetSeconds = seconds End Function End Class 4.4 Object Creation Issues When an object is created, the data members have initial values that depend on where the object is defined. This is exactly the same situation as with non-object variables. For example, if an Integer variable is defined at the module level, its value is guaranteed to be initially zero. In contrast, if an Integer variable is defined within a subroutine or function (without the Static attribute), its initial value is indeterminate. String variables (both the allocated type and BoundedString type) have slightly different rules in that they are guaranteed initally to have zero-length string values no matter where the variable is defined. Similarly, fixed-length strings are guaranteed to have an initial value of a space-filled string with the specified length. These rules apply to the data members of objects (just as they do with structures), again depending on where the object is defined. Beyond these fundamental initialization guarantees, when you define a class you can also define optional constructor methods that initialize the values of some or all of the data members. A constructor method is a subroutine that has the special name _Create. You may define several different constructor methods, all having the name _Create, but each of the constructor overloads must have different formal parameter lists so that the compiler can distinguish between them. The expanded MyTime class definition below includes several constructor methods and the additional code shows how a particular constructor can be specified when an object is instantiated. It is important to note that when a particular constructor executes, the fundamental initialization (described above) will already have been performed. Class MyTime Private hour as Byte Private minute as Byte Private seconds as Single