Access override method and return type modification

The following code works according to the rules of the Overriding method and shows a compilation error. Incompatible return type with Base.aMethod ()

class Base
{
    Integer aMethod()
    {
        return 0;
    }
}
public class OverRidingRules extends Base
{
    protected Number aMethod()
    {
        return 0;
    }
}

But if I change the access modifier Base.aMethod from standard to private, it compiles successfully. Can someone tell me why the compiler is not showing the same error?

+4
source share
1 answer

" " , , 1 . aMethod from Base Integer, , Number, , , Float s. .

, aMethod Base private, / . aMethod OverRidingRules aMethod Base, , , , .

@user3580294 .


1 . , :

class Base {
    Number aMethod() {   // notice the return type is `Number`
        return 0;
    }
}

class OverRidingRules extends Base {
    Integer aMethod() {  // notice the return type is `Integer`
        return 0;
    }
}

, " " , , .

+3

Source: https://habr.com/ru/post/1544005/


All Articles