Java – why is it not allowed to narrow the scope while covering it

In Java, when I rewrite a method, the compiler flags any attempt to reduce visibility to an error For example: I can't override a public method as protected, but I can override a protected method as public

I am interested to know the design decisions / ideas behind this rule

Solution

A subclass should always satisfy the superclass contract See Liskov Substitution Principle

The visibility of the method is part of this contract So anything exposed in a superclass should also be exposed in a subclass

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>