Dima Ciun
Dima Ciun

Reputation: 87

Inheritance private method and public

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

Upvotes: 0

Views: 54

Answers (1)

jhamon
jhamon

Reputation: 3691

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.)

Upvotes: 4

Related Questions