英文:
Inheritance private method and public
问题
以下是翻译好的部分:
让我们说我有基类 A
和扩展它的子类 B
。
类 A
有:
protected int doStuff(List<String> list)
在类 B
中,哪个方法可以覆盖此方法而没有错误?
protected long doStuff(List<String> l)
private int doStuff(Collection<String> c)
public final int doStuff(List<String> l)
protected int doStuff(list1, l2)
我认为是 public final
的方法,但我不确定。
我今天在考试中遇到了这个问题。
英文:
Let 's say I have base class A
and subclass B
that extends it
Class A
got:
protected int doStuff(List<String>list)
In B
which method can override this method without errors?
protected long doStuff(List<String> l)
private int doStuff(Collection<String> c)
public final int doStuff(List<String>l)
protected int doStuff(list1, l2)
I think it's the public final
one but I'm not sure.
I had this question today in an exam
答案1
得分: 4
-
protected long doStuff(List<String> l)
返回类型不同 (long
而不是int
)。这不是重写初始方法。 -
private int doStuff(Collection<String> c)
不能降低继承方法的可见性。而且参数不同。这不是重写初始方法。 -
public final int doStuff(List<String> l)
返回类型相同,参数类型相同。方法的可见性不同,但由于public
可见性大于protected
,所以这是正确的答案。 -
protected int doStuff(list1, l2)
参数数量不同。这不是重写初始方法。(请注意,参数未指定类型,因此此方法原型也无效。)
英文:
1. protected long doStuff(List<String> l)
The returned type is different (long
instead of int
). This is not overwriting the initial method.
2. private int doStuff(Collection<String> c)
You can't reduce the visibility of the inherited method. Plus, the argument is different. This is not overwriting the initial method.
3. public final int doStuff(List<String> l)
The returned type is the same, the argument type is the same. The method visibility is different, but as public
visiblity is greater than protected
, it will works. This is the correct answer.
4. protected int doStuff(list1, l2)
The number of argument is different. This is not overwriting the initial method. (Note there is no type specified for the arguments, so this method prototype is also not valid.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论