Search code examples
rclassoopreference-class

How to create a virtual reference class in R?


I can't find much on virtual/abstract classes in help(ReferenceClasses) - can anyone provide a basic example in creating one? Moreover, how can I specify a virtual method and enforce that child classes must implement it?


Solution

  • Reference classes are S4 classes. SO maybe you should see the help of setClass and Classes:

    Here 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 numeric and base .method is used
    setRefClass( 
      Class="childNum", 
      fields=list( 
        .elt="numeric" 
      ), 
      contains=c("virtC")  
    )
    
    
    ## child 2 
    ## field is char and .method is overwritten
    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"