Defining Classes

The definition of an OOP class (i.e., a class in the style of Java, C#, C++, etc) has three essential parts:

  1. the set of methods that can be invoked on objects from the class;

  2. the fields that contain the information in the object;

  3. other classes that this class extends (often called the super-classes of this class in object-oriented programming).

The OOP package has S software for all of these. Besides ordinary methods and fields, it is possible to define class methods, which are invoked on the class object, and class fields, which are defined in the class object, rather than in the objects created from the class.

Classes are created dynamically, by calling the function defineClass:


defineClass("track")
The call defines a class and creates an object of the same name to contain that definition. Arguments to defineClass can specify fields, methods, class methods, and extends. Alternately, methods defined on the class object specify this information incrementally. Either way is fine, and the incremental definition is a little more readable. Fields are specified by name and by the class that the field should have.

track$defineFields(x = "numeric", y = "numeric")
This specifies two fields, both numeric. The field classes can be either OOP classes or the names of ordinary S classes or data types. Methods are also specified by name. The value associated with the name is a function definition:

track$defineMethod("draw", function() plot(x, y))
This defines a method called draw for class track; if tr1 is an object from this class,

tr1$draw()
invokes the method, which then calls the S function plot with the x and y fields as arguments. Writing functions for methods is different from writing ordinary functions. The object on which the method is invoked is not an argument to the function; as usual in object-oriented programming, the object is implicit in the definition of methods (see the detailed discussion of writing methods).

When a new class extends an existing class, it inherits all the fields and methods of the existing class, but can also override any of these with new definitions. Here is the complete definition of a class trackCurve that extends class track:


defineClass("trackCurve", extends = "track")

trackCurve$defineFields(smooth = "numeric")

trackCurve$defineMethod("draw",  function() {
       super(draw())
       if(length(smooth)>0)
           lines(x, smooth)
   }
   )

Documentation for Classes

Online documentation for a class, using the standard S help() mechanism is produced by invoking the help() method on the class object; e.g.,


track$help()
To produce a shell of documentation for a class, use the makedoc method:

track$makeDoc()
This macro uses the class definition object to generate an outline of documentation, which in R it writes by default to the file with the class name and suffix ".Rd", in this example "track.Rd"
Last modified: Mon Oct 7 11:15:57 EDT 2002