struct's fields are all public? no access control?

Arafel er.krali at gmail.com
Sat Apr 3 09:17:51 UTC 2021


On 2/4/21 23:41, Kagamin wrote:
> On Friday, 2 April 2021 at 18:33:35 UTC, 12345swordy wrote:
>> The private behave differently from other languages does not seemed to 
>> effect many people here.
> 
> AFAIK, it copies java.

Actually no. In java, according to the spec, the encapsulation unit is 
the "top-level" class. The java spec says[1]:

> Otherwise, the member or constructor is declared private. Access is permitted only when the access occurs from within the body of the top level class or interface that encloses the declaration of the member or constructor.

Usually this is translated into once class per file (module, in D), 
because you can only have one *public* top-level class per file, 
(module, in D), and there aren't any free functions, so the question 
just doesn't usually arise.

However, although not really recommended and seldom used, you can 
actually have multiple classes per file, as long as only one of them is 
public (the rest needn't be "private", can be "package"). In this case 
encapsulation works between classes. This is actually quite inconsistent 
and can lead to weird behavior like this:

```java
public class A {
     static private class InnerA {
         private int a = 0;
     }
     static private class InnerB {
         void foo(InnerA a) {
             // InnerA can access InnerB private members
             a.a = 1;
         }
     }

     void foo(B b) {
         // But A can't acces B private members
         b.b = 1; // A.java:14: error: b has private access in B
     }
}

class B {
     private int b = 0;
}
```

So all in all, D's behavior is at least consistent and something one can 
get easily used to.

[1]: https://docs.oracle.com/javase/specs/jls/se16/html/jls-6.html#jls-6.6.1


More information about the Digitalmars-d mailing list