覆盖方法时,为什么我可以增加访问而不能减少访问? [英] When overriding a method, why can I increase access but not decrease it?

查看:87
本文介绍了覆盖方法时,为什么我可以增加访问而不能减少访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Java会指定覆盖方法的访问说明符可以比覆盖方法允许更多但不能更少的访问?例如,超类中的受保护实例方法可以在子类中公开,但不能私有。

Why does Java specify that the access specifier for an overriding method can allow more, but not less, access than the overridden method? For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

推荐答案

OOP的基本原理:子类是父类的完整实例,因此必须提供与父类至少相同的接口。使受保护的/公共的东西不那么明显将违反此想法;您可以使子类不能用作父类的实例。

It's a fundamental principle in OOP: the child class is a fully-fledged instance of the parent class, and must therefore present at least the same interface as the parent class. Making protected/public things less visible would violate this idea; you could make child classes unusable as instances of the parent class.

这篇关于覆盖方法时,为什么我可以增加访问而不能减少访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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