r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
407 stars 56 forks source link

Accessing private methods of superclass #45

Closed jankowtf closed 9 years ago

jankowtf commented 9 years ago

Not implementing this seems like a deliberate choice (I tried super$private$foo() which does not work) and so I'm guessing it's against general OOP principles that subclasses are able to access the private methods of their superclass(es).

But would that really be such a bad thing? After all, inheritance is a systematic way to extend the features of a certain class while re-using those already present. But if all private methods of class being extended are "lost"/not accessible for the subclass, then doesn't this result in unnecessary code duplication (in the sense that the required private methods would have to be defined again as private methods in the subclass)?

Might just be me, but I would consider a subclass calling methods from its superclass to be something rather "internal" as opposed to, say, a client application using a certain class instance (in which case you would only want the public methods to be accessible, of course).

Suppose that in A, bar() has a pure internal character in and checks the validity of certain field values so you would not want to make it public. But that way its not accessible for B and I would thus need to define the exact same method again in B.

require("R6")
A <- R6Class(
  classname = "A",
  public = list(
    foo = function() {
      "foo"
    }
  ),
  private = list(
    bar = function() {
      "bar"
    }
  )
)

B <- R6Class(
  classname = "B",
  inherit = A,
  public = list(
    foobar = function() {
      print(super$foo())
      print(super$private$bar())
    }
  )
)

x <- B$new()
x$foobar()
wch commented 9 years ago

In super, both the public and private methods are available. So in your example, you could just use super$bar().

jankowtf commented 9 years ago

Aha! Thanks a lot for that clarification!

wch commented 9 years ago

Great, glad it helps!