Java继承方面的保护与公共 [英] Protected vs Public in terms of Inheritance in Java

查看:58
本文介绍了Java继承方面的保护与公共的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建超类时,何时应该在Java中使用Public over Protected in Java,如果程序运行时没有任何受保护的访问修饰符集,是否需要将其更改为Public?

When should one use Public over Protected in Java when creating Superclasses, if a program runs without any problems with a Protected access modifier set is there any need to change it to Public?

推荐答案

您应遵循最低权限原则.

这意味着应该为成员分配该程序正常运行所需的最低访问权限.

This means that members should be assigned the minimum accessibility needed for the program to work.

如果不相关的类需要访问,则将其设为 public .通常,仅对提供托管访问数据的方法执行此操作.

If an unrelated class needs access, make it public. Typically this is done only for methods that provide managed access to data.

如果要完全信任子类来处理数据,并且需要该子类正常运行,则可以使该成员受到 protected 的保护.

If the subclass is to be completely trusted in manipulating the data, and it needs it to work properly, you can make the member protected.

否则,将其设为 private ,这样其他任何类都无法访问它(无需通过其他有助于封装数据的更易访问的方法).

Else, make it private, so no other class can access it (without going through other more accessible methods that help encapsulate the data).

如果您的程序受保护时运行良好,则不要将其设为 public .考虑使用访问它的受 protected 方法将其设为 private ,以更好地封装数据.

If your program works well when it's protected, then do not make it public. Consider making it private, with protected methods that access it, to encapsulate the data better.

这篇关于Java继承方面的保护与公共的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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