为什么在覆盖时不允许缩小方法的范围 [英] Why is it not allowed to narrow down scope of a method while overriding

查看:150
本文介绍了为什么在覆盖时不允许缩小方法的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,当我覆盖一个方法时,编译器会将任何将可见性范围缩小的尝试标记为错误。例如:我不能将公共方法覆盖为受保护,而我可以将受保护的方法覆盖为公共方法。

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 I can override a protected method as public.

我有兴趣了解背后的设计决策/思考这个规则。

I am interested in knowing the design decision/thinking behind this rule.

推荐答案

子类应始终满足超类的约定。请参阅 Liskov替换原则

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.

这篇关于为什么在覆盖时不允许缩小方法的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆