Java Programming - Declarations and Access Control - Discussion

12. 

class A 
{  
    protected int method1(int a, int b) 
    {
        return 0; 
    } 
}
Which is valid in a class that extends class A?

[A]. public int method1(int a, int b) {return 0; }
[B]. private int method1(int a, int b) { return 0; }
[C]. public short method1(int a, int b) { return 0; }
[D]. static protected int method1(int a, int b) { return 0; }

Answer: Option A

Explanation:

Option A is correct - because the class that extends A is just simply overriding method1.

Option B is wrong - because it can't override as there are less access privileges in the subclass method1.

Option C is wrong - because to override it, the return type needs to be an integer. The different return type means that the method is not overriding but the same argument list means that the method is not overloading. Conflict - compile time error.

Option D is wrong - because you can't override a method and make it a class method i.e. using static.


Jatin Chanchlani said: (Dec 30, 2011)  
In case of method overriding, the return type of the overridding method must be the same or a subtype of the return type declared in the original method in the super class.

So in this case option C is also correct.

Snehal Phatangare said: (Nov 4, 2012)  
NO. The return type of the overridding method cannot be a sub-type of the method over-ridden. The method signature has to be exactly the same.

Neha said: (Nov 12, 2014)  
As I know the overriding method should have access specifier as same or less restrictive but here protected is overridden as public. How?

Raman said: (Sep 13, 2015)  
Can I override private method?

Sanchita said: (Mar 11, 2017)  
The access level cannot be more restrictive than the overridden method's access level.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.