0

Should I always specify a class as sealed if it's the last in the inheritance list? As an example, say I've got 3 classes, Foundation, Building, and House.

public class Foundation
{
    // Base class
}

public class Building : Foundation
{
    // Derived from Foundation
}

public sealed class House : Building
{
    // Last in the inheritance tree
}

Is it about safety when I say that I don't want anyone to inherit from House while House itself is inheriting from Building?

Alexej
  • 97
  • 1
  • 1
  • 6
  • Yes, if you want your consumer not to inherit you can mark it as `sealed` in order to restrict – Rahul Aug 20 '16 at 18:40
  • Think about implications about an inheritable class. Documentation, extension points, design of a modifiable class... – Adriano Repetti Aug 20 '16 at 18:43
  • Are you asking "why would someone seal a class?" or "what does sealing a class do?" The first is purely opinionated, the second can be definitely answered. – Lasse V. Karlsen Aug 20 '16 at 18:47

3 Answers3

2

From what I have read (can't remember the name of the book, though it was from 2010), unless class is designed to be inherited from, it should be marked sealed as to prevent to other developers inheriting from it and then running into roadblocks, because some methods are not virtual.

CrudaLilium
  • 654
  • 7
  • 18
0

Should I always specify a class as sealed if it's the last in the inheritance list?

There is no specific answer for this question. There might be some scenarios, like what you have mentioned. You don't want anyone inherit from House class. For this particular scenario you should make the House class sealed. To proceed with some more knowledge you can follow this

There can be some other cases when you are developing a software. Are you stick with your current features or it can be changed over the period. Then you should think differently. For further learning you can follow this

PaulShovan
  • 2,140
  • 1
  • 13
  • 22
0

Let's say you have a MyDivisor class with SetDivisor and GetDivisor methods. The SetDivisor method is implemented as follows:

public void SetDivisor(int divisor)
{
    if (divisor != 0)
    {
        _divisor = divisor; // `_divisor` is a field of the class
    }
}

Even though you might think there is no way of the divisor being zero, someone might inherit your MyDivisor class and use the new keyword to hide your method (which is not virtual). The derived MyEvilDivisor class has the following implementation of SetDivisor:

new public void SetDivisor(int divisor)
{
    _divisor = divisor;
}

Now someone can write:

var divisor = new MyEvilDivisor();
divisor.SetDivisor(0);
int i = 5/(divisor.GetDivisor());

If you seal your class, there will be no way to inherit it and change the behavior of SetDivisor, which will not lead to unexpected runtime errors in the application that will surely happen when using MyEvilDivisor. I guess this is an example of thinking about safety.

Kapol
  • 6,383
  • 3
  • 21
  • 46