Can I prevent class inheritance by a non-abstract object?

Consider the following classes:

public abstract class Planet
{
    protected abstract Material Composition { get; }
}

public abstract class TerrestrialPlanet : Planet
{
    protected override Material Composition
    {
        get
        {
            return Type.Rocky;
        }
    }
}
public abstract class GasGiant : Planet
{
    protected override Material Composition
    {
        get
        {
            return Type.Gaseous;
        }
    }
}

Is there a way to prevent the inheritance of a non-abstract object directly from the class Planet?

In other words, can we ensure that any class that directly inherits from Planetis abstract?

// ok, because it doesn't directly inherit from Planet
public class Earth : TerrestrialPlanet { ... }

// ok, because it is abstract
public abstract class IcyPlanet : Planet { ... }

// we want to prevent this
public class Pluto : Planet { ... }
+4
source share
1 answer

No, you cannot stop a non-abstract class from inheriting the given public class that you create.

, , , , internal, , . , , , .

+5

Source: https://habr.com/ru/post/1620432/


All Articles