static class

Ben Davis entheh at cantab.net
Sun Feb 17 15:26:37 PST 2013


On 17/02/2013 22:25, Jonathan M Davis wrote:
> On Sunday, February 17, 2013 23:00:19 Michael wrote:
>>> That's not the meaning of static in that context.
>>
>> As I understand a static class can't be instantiated.
>
> I have no idea how you came to that conclusion.

In fairness, it is the natural guess you'd make if you haven't actively 
used nested instance classes and understood how the outer instance 
pointer is stored. We use Java at work (same mechanism as D), and hardly 
anyone actually knows to write 'static' when they create a nested class 
that they intend to be POD. :)

> That's not what it means for a
> class to be static at all. The only place that static has any effect on classes
> is for nested classes. A static, nested class is like any other class except
> that it's inside another class, which affects its path. e.g.
>
> module b;
>
> class C
> {
>      static class W
>     {
>     }
> }
>
> W is therefore b.C.W, whereas if it were not nested inside of C but next to it
> within the same module, then it would be b.W.
>
> However, non-static nested classes are associated with an instance of the
> outer class, and therefore only one can exist per class instance.

That's not true, is it? You can make as many nested instances as you 
like. It's just that there must be some outer instance available at the 
time of construction (which can be a new one each time or the same one 
every time or anything in between).

> However, it
> also has access to that outer class instance through the property outer. e.g.
>
> class C
> {
>      class R
>      {
>          void func()
>          {
>              //Sets the variable in the instance of
>              //C that it's associated with.
>              outer.i = 7;
>          }
>      }
>
>      int i;
> }

Is it possible to write someInstanceOfR.outer? I've occasionally wanted 
Java to have that feature, and ended up storing the 'outer' reference 
manually. Though this probably means I was writing bad code; I can't 
remember. :D


More information about the Digitalmars-d-learn mailing list