R6: Accessing private methods of superclass

Created on 17 Feb 2015  ·  3Comments  ·  Source: r-lib/R6

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()

Most helpful comment

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

All 3 comments

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

Aha! Thanks a lot for that clarification!

Great, glad it helps!

Was this page helpful?
0 / 5 - 0 ratings