Why do private member variables behaved like protected in the same module when creating deriving class?
Neia Neutuladh
neia at ikeran.org
Fri Oct 26 18:57:00 UTC 2018
On Fri, 26 Oct 2018 18:16:38 +0000, 12345swordy wrote:
> Why private member variables behave like protected member variables in
> the same module? Can you explain your thought process when it comes to
> this design decision Walter Bright? Is there no way to mark the private
> member variables as "final" in the same module?
>
> -Alex
D's `private` within a module is identical to Java's `private` within a
class and its nested classes. The following is valid Java:
// Protections.java
public class Protections {
private void foo() { System.out.println("foo"); }
public static class Bar {
public void foo(Protections p) { p.foo(); }
private void bar() { System.out.println("bar"); }
}
public static class Baz {
private void bar(Bar b) { b.bar(); }
}
public static void main(String[] args) {
new Bar().foo(new Protections());
new Baz().bar(new Bar());
}
}
If you maintain a D module, you are expected to maintain the whole module,
so you should be able to determine when it's valid to access a private
member. And this is useful.
This is the same as Java's opinion that, if you wrote a class, you should
be responsible its nested classes too, and vice versa, so you should be
able to access private members across those classes. Also because it's
useful.
C++ uses `friend` instead: you explicitly mark what other types and
functions can use your private variables.
C# has stricter `private` like you're expecting. Python has a way to make
it annoying to refer to a class member.
So there's no clear winning way of doing things. D has one way of working
that's rather useful but somewhat surprising (probably largely because of
Java programmers who aren't familiar with some aspects of Java, I'm
guessing). The less surprising alternative stops you from doing some
useful things.
More information about the Digitalmars-d
mailing list