简体   繁体   English

如何防止继承类实例

[英]How to prevent inherited classes instances

I want to force any class not to be able to create a new instance if it inherits a specific base class, so how this base class should look like?如果继承特定的基础 class,我想强制任何 class 不能创建新实例,那么这个基础 class 应该是什么样子?

The following code is in java.以下代码在 java 中。 just to give you an Example只是给你一个例子

Base class has an exception on the constructor.基础 class 在构造函数上有异常。

public class BaseClass 
{
    public BaseClass()
    {
        throw new AssertionError();
    }
}

The child class extending the base class but if you create an object of it it will give u an exception.子 class 扩展了基础 class 但是如果你创建一个 object 它会给你一个例外。

public class MainClass extends BaseClass 
{
    public MainClass()
    {

    }

    public static void main(String[] args) {
        MainClass c = new MainClass();
    }
}

You want to seal your base class.你想密封你的基地 class。

public sealed class BaseClass
{
    public BaseClass(){};
}



public class SubClass : BaseClass
{
    public SubClass(){};
}

This will throw a compiler error because you cannot inherit from a sealed base.这将引发编译器错误,因为您不能从密封的基础继承。

You can't specify that in the baseclass, any deriving class is self responseable, if it wants to present the ability to be derived from, than you can't do anything about it.您不能在基类中指定任何派生的 class 都是可自我响应的,如果它想要提供派生的能力,那么您就无能为力了。

you can declare the base class as const - that way other classes cant extend it.您可以将基础 class 声明为 const - 这样其他类就无法扩展它。

You can't do this.你不能这样做。 Please specify why you want to do this.请说明您为什么要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM