How to create a virtual reference class in R?

I can't find much in virtual / abstract classes in help(ReferenceClasses). Can someone provide a basic example on creation? Moreover, how can I specify a virtual method and ensure that child classes implement it?

+4
source share
1 answer

Reference classes are S4 classes. SO, maybe you should see help setClassand Classes:

Here is an example of a dummy example:

# virtual Base Class
setRefClass( 
  Class="virtC", 
  fields=list( 
    .elt="ANY" 
  ),
  methods = list(
    .method = function(){
      print("Base virtual method is called")
    }
  ), 
  contains=c("VIRTUAL") 
) 

## child 1
## field as char and .method is overwritten
setRefClass( 
  Class="childNum", 
  fields=list( 
    .elt="numeric" 
  ), 
  contains=c("virtC")  
)


## child 2 
## field is numeric and base .method is used
setRefClass( 
  Class="childChar", 
  fields=list( 
    .elt="character" 
  ), 
  methods = list(
    .method = function(){print('child method is called')}
  ), 
  contains=c("virtC") 
) 
##  new('virtA')          ## thros an error can't isntantiate it
a = new("childChar",.elt="a")
b =   new("childNum",.elt=1)

b$.method()
[1] "Base virtual method is called"

a$.method()
[1] "child method is called"
+3
source

All Articles