If someone is able, can you tell me if there is a better way to do this?
More specifically, do I have to rewrite all of the data members stuff  and
extend stuff of parent class in the child class? See below. Thanks in
advance!

Example 1:

setConstructorS3("ClassA", function(A,x) {
  if(missing(A))A=15;
  if(missing(x))x=NA;
  extend(Object(), "ClassA",
    .size = A,
    .x=x
  )
})
setMethodS3("getSize", "ClassA", function(this,...) {
  this$.size;
})
setMethodS3("getX", "ClassA", function(this,...) {
  this$.x;
})

setConstructorS3("ClassB", function(A,x,bData) {
  if(missing(bData))bData = NA;
  extend(ClassA(), "ClassB",
    .bData = bData
  )
})
setMethodS3("getBData", "ClassB", function(this,...) {
  this$.bData;
})

Usage:
> b = ClassB(13,100,6)
> b$getSize()          # I expected to get 13.
[1] 15
> b$getBData()
[1] 6
> b$getX()
[1] NA            # Same thing here. I expected 100.


I corrected it by rewriting the ClassA data member defaults and the ClassA
extend() stuff within the ClassB class.

Example 2:

setConstructorS3("ClassA", function(A,x) {
  if(missing(A))A=15;
  if(missing(x))x=NA;
  extend(Object(), "ClassA",
    .size = A,
    .x=x
  )
})
setMethodS3("getSize", "ClassA", function(this,...) {
  this$.size;
})
setMethodS3("getX", "ClassA", function(this,...) {
  this$.x;
})

setConstructorS3("ClassB", function(A,x,bData) {
  if(missing(bData))bData = NA;
  if(missing(A))A=15;                          #added
  if(missing(x))x=NA;                             #added
  extend(ClassA(), "ClassB",
    .bData = bData,
    .x=x,                                           #added
    .size=A                                         #added
  )
})
setMethodS3("getBData", "ClassB", function(this,...) {
  this$.bData;
})

> b = ClassB(13,100,6)
> b$getSize()
[1] 13
> b$getBData()
[1] 6
> b$getX()
[1] 100

Thanks for your help!

Ben

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to