为什么这里的 String 构造函数应该是 protected 而不是 private 呢?
我对这个 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果构造函数是私有的,Beta 将如何调用
super(a)
?所以它不能是私有的......但你是对的:如果它是受保护的,那么同一包中的其他类型确实可以调用
换句话说,我不相信私有< /code> 是正确的答案,但我不相信有正确的答案。您不能将可见性限制为仅 Java 中的派生类。
编辑:我明白了:)
使
Alpha
抽象,并用构造函数做你喜欢的事情,只要它对Beta
可见(public 或
protected
都可以)。这样第三个条件就自动为真,因为永远不会有任何Alpha
的实例!现在,这确实需要对第 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 callIn 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 toBeta
(public
orprotected
is fine). That way the third condition is automatically true, because there will never be any instances of justAlpha
!Now, this does require a bit of a weaselly interpretation of point 1. I would argue that an instance of
Beta
is an instance ofAlpha
(after all,instanceof
will return true :) so that satisfies point 1, but an instance ofBeta
is not "an object of typeAlpha
" so point 3 is still okay.