Sealed classes - would you want them in D?

Piotr Mitana the.mail.of.mi2 at gmail.com
Fri May 11 08:38:31 UTC 2018


On Thursday, 10 May 2018 at 14:48:23 UTC, rikki cattermole wrote:
> module foo;
> 
> class A { }
> 
> final class B : A {    }
> 
> in one module, he wants to be able to create a new
> 
> final class C : B {    }
> 
> and keep class B as final so that no one else can extend it in 
> another module.

Not entirely. Let's use code to explain. We have:

     module pack.foo;

     sealed class A {}
     class B : A {}  // Legal
     final class C : A {}  // Legal

     sealed(pack) class D {}
     class E : D {}

     ===================

     module pack.bar;

     class F : A {}  // Illegal, A is sealed
     class B1 : B {}  // Legal, B is not sealed - A is
     class C1 : C {}  // Illegal of course, as C is final

     class D1 : D {}  // OK, D is package-sealed
     class E1 : E {}  // OK, E is neither sealed nor final

     ===================

     module anotherpack.baz;

     class G : A {}  // Illegal, A is sealed
     class B2 : B {}  // Legal, B is not sealed
     class C2 : C {}  // Illegal, C is final

     class D2 : D {}  // Illegal, D is package-sealed for pack
     class E2 : E {}  // Legal, E is neither sealed nor final

In general: sealed means a special case of neither private, 
protected nor final and it probably could not be achieved with a 
combination of these two.

Sealed does not mean private, as access to the class is not 
restricted in any way. It is also not transitive - class 
extending a sealed class can be extended freely unless they are 
sealed as well or final. Given those classes:

     sealed class Pet {}
     class Cat : Pet {}
     class Dog : Pet {}

we can implement a different types of Cats and Dogs - but 
creating a Ferret or Parrot is illegal. So it may be used to 
limit one level of inheritance, but retain the freedom to extend 
the few defined types. Making the base class private would not be 
OK, as we don't want to restrict the access to that class.


More information about the Digitalmars-d mailing list