Java Programming - Declarations and Access Control - Discussion

Discussion Forum : Declarations and Access Control - General Questions (Q.No. 12)
12.
class A 
{  
    protected int method1(int a, int b) 
    {
        return 0; 
    } 
}
Which is valid in a class that extends class A?
public int method1(int a, int b) {return 0; }
private int method1(int a, int b) { return 0; }
public short method1(int a, int b) { return 0; }
static protected int method1(int a, int b) { return 0; }
Answer: Option
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.

Discussion:
5 comments Page 1 of 1.

Jatin Chanchlani said:   1 decade ago
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:   1 decade ago
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:   1 decade ago
As I know the overriding method should have access specifier as same or less restrictive but here protected is overridden as public. How?

Sanchita said:   9 years ago
The access level cannot be more restrictive than the overridden method's access level.

Raman said:   1 decade ago
Can I override private method?

Post your comments here:

Your comments will be displayed after verification.