Why is it not allowed to narrow down scope of a method while overriding

后端 未结 4 1850
北海茫月
北海茫月 2021-01-17 09:27

In Java, when I override a method the compiler flags off any attempt to narrow down the visibility as an error. For ex: I can\'t override a public method as protected, while

4条回答
  •  悲&欢浪女
    2021-01-17 10:12

    A subclass should always satisfy the contract of the superclass. See Liskov Substitution principle.

    The visibility of methods is part of this contract. So anything publicly visible in the superclass should be public in the subclass as well.

提交回复
热议问题