Deconstructor can not be overriden ? Was: Deconstruction patterns

forax at univ-mlv.fr forax at univ-mlv.fr
Tue Mar 7 17:53:52 UTC 2023


----- Original Message -----
> From: "Brian Goetz" <brian.goetz at oracle.com>
> To: "Remi Forax" <forax at univ-mlv.fr>
> Cc: "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Sent: Tuesday, March 7, 2023 3:31:26 PM
> Subject: Re: Deconstructor can not be overriden ? Was: Deconstruction patterns

>> Why deconstructor can not be overriden ?
>>
>>
> Deconstructors are not inherited, just as constructors are not
> inherited.  However, just as with constructors, a subclass is free to
> declare (or not!) a deconstructor with the same descriptor.
> 
> However, deconstructors are still _applicable_ to subtypes:
> 
>     class A {
>         public matcher A(String s) { ... }
>     }
> 
>     class B extends A {
>         // no matchers
>     }
> 
>     B b = new B(monkey);
> 
>     switch (b) {
>         case A(var s): ...  // exhaustive on B
>     }
> 
> Since a B is-a A, the A pattern is applicable and unconditional on all
> instances of A, including instances of B.  This allows the client to
> discriminate more carefully (assuming B has a similar dtor):
> 
>     switch (a) {
>         case B(var s): ...  B logic ...
>         case A(var s): ...  catch-all A logic ...
>     }


Conceptually that violate the principle of encapsulation, you can access to the state of B without using a method of B.

You talk about de-constructors as the dual of constructors. It can be a useful metaphor but it does not mean that a de-constructor mirrors all the features of a constructor.

A de-constructor is also a bundle of accessors, like if you were able to call all the accessors at once.
Accessors are overridable for a good reason, otherwise you can leak the internal state.

By example,

class A {
  int value;

  A(int value) { this.value = value; }

  int getValue() { return value; }

  public matcher A(int value) { ... }
} 

class B extends A {
  B(int value) {
   super(-value);
  }

  int getValue() { return -value; }

  // here we need to override the matcher otherwise the user code can see the internal state !
}


regards,
Rémi


More information about the amber-spec-experts mailing list