defineClass: Define a new class

Description Usage Arguments Details See Also Examples

View source: R/DC-defineClass.R

Description

This is an experimental implementation of reference classes. Use defineRefClass or retList instead. defineClass has side effects. The constructor is the return value of defineClass.

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
defineClass(name, expr, contains = NULL)

private(x)

## S4 method for signature 'public'
private(x)

public(x = NULL, validity = function(x) TRUE)

## S4 method for signature ''function''
public(x = NULL, validity = function(x) TRUE)

## S4 method for signature 'private'
public(x = NULL, validity = function(x) TRUE)

## S4 method for signature 'public'
public(x = NULL, validity = function(x) TRUE)

Arguments

name

character name of the class

expr

expression

contains

character name of class from which to inherit

x

an object made public

validity

function to check the validity of an object

Details

defineClass creates a S4-Class which can be used for standard S4 method dispatch. It will also set the method 'initialize' which need not to be changed. If you want to have some operations carried out on initialization use a function definition named init as part of expr. The return value from defineClass is the constructor function. It has the argument ... which will be passed to init.

All classes defined with defineClass inherit from class "aoos" which is a S4-class containing an environment. In that environment expr is evaluated; for inheritance, all expr from all parents will be evaluated first.

Everything in expr will be part of the new class definition. A leading dot in a name will be interpreted as private. You can use public and private to declare private and public members explicitly. If x in a call to public is a function it will be a public member function (method). For any other class the return value of public is a get and set method. If called without argument it will get the value, if called with argument it will set the value. You can define a validity function which will be called whenever the set method is called. Objects which inherit from class environment can be accessed directly, i.e. not via get/set methods. If you want to access fields without get/set methods, you can use the class Accessor-class.

See Also

Accessor-class, Binary-class, Show-class

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
test <- defineClass("test", {
  x <- "Working ..."
  .y <- 0
  doSomething <- public(function() {
    self$.y <- .y + 1
    cat(x(), "\n")
    invisible(self)
  })
})
instance <- test()
## Not run: 
instance$.y # error

## End(Not run)
instance$doSomething()$doSomething()
instance$x()
instance$x(2)
instance$x()

# Example for reference classes as field
MoreTesting <- defineClass("MoreTesting", {
  refObj <- test()
})
instance <- MoreTesting()
instance$refObj$x()

wahani/aoos documentation built on May 27, 2017, 11:54 p.m.