Deconstructor can not be overriden ? Was: Deconstruction patterns

Brian Goetz brian.goetz at oracle.com
Tue Mar 7 14:31:26 UTC 2023


> 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 ...
     }

But, your question raises a good translation question: should we 
translate a dtor as an instance member (like <init>) and then ensure 
that it is only invoked by `invokespecial`, or should we translate it as 
a static?

> Does it means that we can not have a deconstructor on an interface ?

It does not mean that.  Indeed, deconstructors in interfaces are great:

     Map<String, String> kvStore = ...
     for (Map.Entry(var k, var v) : kvStore.entrySet()) { ... }




More information about the amber-spec-experts mailing list