Concepts of Programming Languages

(Sean Pound) #1
11.4 Language Examples 499

}
private int degreeDays;

...
}
...
Weather w = new Weather();
int degreeDaysToday, oldDegreeDays;
...
w.DegreeDays = degreeDaysToday;
...
oldDegreeDays = w.DegreeDays;


In the class Weather, the property DegreeDays is defined. This property pro-
vides a getter method and a setter method for access to the private data member,
degreeDays. In the client code following the class definition, degreeDays is
treated as if it were a public-member variable, although access to it is available
through the property only. Notice the use of the implicit variable value in the
setter method. This is the mechanism by which the new value of the property
is referenced.
The stack example is not shown here in C#. The only difference between
the Java version in Section 11.4.4.1 and the C# version is the output method
calls and the use of bool instead of boolean for the return type of the empty
method.

11.4.6 Abstract Data Types in Ruby


Ruby provides support for abstract data types through its classes. In terms of
capabilities, Ruby classes are similar to those in C++ and Java.

11.4.6.1 Encapsulation
In Ruby, a class is defined in a compound statement opened with the class
reserved word and closed with end. The names of instance variables have
a special syntactic formthey must begin with at signs (@). Instance meth-
ods have the same syntax as functions in Ruby: They begin with the def
reserved word and end with end. Class methods are distinguished from
instance methods by having the class name appended to the beginning of
their names with a period separator. For example, in a class named Stack,
a class method’s name would begin with Stack. Constructors in Ruby are
named initialize. Because the constructor cannot be overloaded, there
only can be one per class.
Classes in Ruby are dynamic in the sense that members can be added at
any time. This is done by simply including additional class definitions that
specify the new members. Moreover, even predefined classes of the language,
such as String, can be extended. For example, consider the following class
definition:
Free download pdf