gpt4 book ai didi

java - 为什么java抽象类中需要Protected构造函数

转载 作者:行者123 更新时间:2023-11-30 07:40:49 25 4
gpt4 key购买 nike

在查看 java 代码时,我看到抽象类的构造函数是 protected 。

public abstract class A {
protected A() {

}
}

什么

Abstract means to me is that you can't create the instance of this class and use this class after extending

.

And protected constructor also ensures that.

做两件事的意义何在,一是使构造函数 protected ,二是使类抽象以解决相同的目的。

最佳答案

的确,减少抽象类中构造函数的可见性(从 publicprotected)并没有改变代码无法直接实例化抽象类的问题。

然而,这不是重点。将构造函数设为 protected 只是为了控制作用域,就像将成员属性设为私有(private)一样。

这是同一个类的修改版本,表明重点不是要阻止实例化:

public abstract class A {
protected A() {
this(0);
}
private A(int a) {
// not accessible to anyone but members of A
// the point is not to prevent instantiation, but to restrict access
}
}

如果使构造函数 protected 是为了防止实例化,那么有人可能会争辩说,在抽象类本身或其子类中实例化是可能的。

关于java - 为什么java抽象类中需要Protected构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56948041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com