继承私有方法和公共方法

huangapple go评论57阅读模式
英文:

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&lt;String&gt;list)

In B which method can override this method without errors?

protected long doStuff(List&lt;String&gt; l)
private int  doStuff(Collection&lt;String&gt; c)
public final int doStuff(List&lt;String&gt;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

  1. protected long doStuff(List<String> l)
    返回类型不同 (long 而不是 int)。这不是重写初始方法。

  2. private int doStuff(Collection<String> c)
    不能降低继承方法的可见性。而且参数不同。这不是重写初始方法。

  3. public final int doStuff(List<String> l)
    返回类型相同,参数类型相同。方法的可见性不同,但由于 public 可见性大于 protected,所以这是正确的答案。

  4. protected int doStuff(list1, l2)
    参数数量不同。这不是重写初始方法。(请注意,参数未指定类型,因此此方法原型也无效。)

英文:

1. protected long doStuff(List&lt;String&gt; l)

The returned type is different (long instead of int). This is not overwriting the initial method.

2. private int doStuff(Collection&lt;String&gt; 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&lt;String&gt; 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.)

huangapple
  • 本文由 发表于 2020年7月28日 16:01:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63129546.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定