有一个抽象类的公共构造函数有很好的理由 [英] Are there good reasons for a public constructor of an abstract class

查看:220
本文介绍了有一个抽象类的公共构造函数有很好的理由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不可能通过直接调用抽象类的构造函数来创建对象。 抽象类的构造函数只能从派生类中调用。因此,我认为抽象类的构造函数必须是 protected 或package-private(后者用于限制使用一个构造函数到包中的派生类)。但是Java允许抽象类的构造函数为 public

It is not possible to create an object by directly calling the constructor of an abstract class. The constructor of an abstract class can be called only from a derived class. It therefore seems to me that constructors of an abstract class must be either protected or package-private (the latter for the unusual cases of restricting use of a constructor to derived classes within the package). Yet Java allows the constructor of an abstract class to be public.

在任何情况下,抽象类的构造函数声明为 public ,而不是 protected 或package-private?

Are there any circumstances in which it is useful to declare the constructor of an abstract class to be public, rather than protected or package-private?

的问题抽象类构造函数访问修饰符:显然,您可以声明一个构造函数为 public ;我想知道是否有任何好的原因。在我看来,没有。我看到 C#也有类似的特性

This is not quite a duplicate of the question "Abstract class constructor access modifier": clearly you can declare a constructor to be public; I want to know whether there is ever any good reason to do so. It seems to me that there is not. I see that C# has a similar peculiarity.

推荐答案

对于java,答案是一样的:

The answer is the same for java:


这是没有理由为抽象类的公共构造函数。我假设编译器没有抱怨的原因很简单,他们只是没有花时间覆盖,因为它是无关紧要的,如果它是public或protected。 (来源

不能从除直接子类之外的任何方法调用抽象类的构造函数。

You can't call a constructor of an abstract class from anything other than a direct subclass.

因此,为抽象类构造函数的访问修饰符添加特殊规则不会对语言添加有用的东西。

So adding a special rule for access modifiers of constructors of abstract classes wouldn't add something useful to the language.

一个的东西看起来像这个规则的异常 - 如果抽象类只定义一个默认构造函数,那么子类不必实现构造函数:这是合法的:

One thing that looks like an exception from this rule - if the abstract class only defines a default constructor, then the subclass does not have to implement a constructor: this is legal:

public abstract class A {
  public A() {}
}

public class B extends A {}

通过调用 new B() - 但请注意,我们仍然创建 B ,而不是 A 。再次,如果 A 中的构造函数是public或protected,则无关紧要。

So we can create a B by calling new B() - but note, that we still create a B and not an A. And, again, it doesn't matter if the constructor in A is public or protected. It just shouldn't be private, but the compiler will notice and complain...

实际上,我们在上调用一个不可见公共默认构造函数, B ,它执行一个简单的 super()调用...

Actually we invoke an "invisible" public default constructor on B which does a simple super() call...

这篇关于有一个抽象类的公共构造函数有很好的理由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆