为什么这里的 String 构造函数应该是 protected 而不是 private 呢?

发布于 2024-09-24 19:54:58 字数 279 浏览 2 评论 0原文

我对这个 SCJP 练习问题有点困惑,特别是第 5 行(使用 String 构造函数)。我认为它应该是私有的,但解决方案是“受保护的”。我认为受保护的访问不能满足所有 Alpha 实例将 String alpha 设置为 A 的要求。如果构造函数受保护,则 alpha 包中的任何其他类,或者 Alpha 的任何子类(无论包如何)都可以调用它并且将 alpha 设置为任何它想要的值。阿米里特?谁能澄清一下吗?谢谢!

替代文字

I'm a bit stuck on this SCJP practice question, specifically line 5 (with the String constructor). I thought it should be private, but the solution is 'protected'. I think protected access would not satisfy the requirement that all Alpha instances have the String alpha set to A. If the constructor is protected, then any other class that's also in package alpha, OR any subclass of Alpha regardless of package, can invoke it and set alpha to whatever it wants. Amirite? Can anyone clarify? Thanks!

alt text

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆里有你的影子 2024-10-01 19:54:58

如果构造函数是私有的,Beta 将如何调用 super(a)

所以它不能是私有的......但你是对的:如果它是受保护的,那么同一包中的其他类型确实可以调用

new Alpha("some other value")

换句话说,我不相信私有< /code> 是正确的答案,但我不相信有正确的答案。您不能将可见性限制为 Java 中的派生类。

编辑:我明白了:)

使 Alpha 抽象,并用构造函数做你喜欢的事情,只要它对 Beta 可见(public 或 protected 都可以)。这样第三个条件就自动为真,因为永远不会有任何Alpha的实例!

package alpha;
public abstract class Alpha {
    final String alpha;
    Alpha() { this("A"); }
    public Alpha(String a) { alpha = a; }
}

package beta;

public class Beta extends alpha.Alpha {
    public Beta(String a) { super(a); }
}

现在,这确实需要对第 1 点进行一些狡猾的解释。我认为 Beta 的实例是 Alpha 的实例code> (毕竟,instanceof 将返回 true :),因此满足第 1 点,但是 Beta 的实例不是“类型的对象>Alpha”所以第3点仍然可以。

If the constructor were private, how would Beta call super(a)?

So it can't be private... but you're right: if it's protected then other types in the same package could indeed call

new Alpha("some other value")

In other words, I don't believe private is the right answer, but I don't believe there is a right answer. You can't limit visibility to only derived classes in Java.

EDIT: I've got it :)

Make Alpha abstract, and do what you like with the constructor, so long as it's visible to Beta (public or protected is fine). That way the third condition is automatically true, because there will never be any instances of just Alpha!

package alpha;
public abstract class Alpha {
    final String alpha;
    Alpha() { this("A"); }
    public Alpha(String a) { alpha = a; }
}

package beta;

public class Beta extends alpha.Alpha {
    public Beta(String a) { super(a); }
}

Now, this does require a bit of a weaselly interpretation of point 1. I would argue that an instance of Beta is an instance of Alpha (after all, instanceof will return true :) so that satisfies point 1, but an instance of Beta is not "an object of type Alpha" so point 3 is still okay.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文