Java OOP公共vs私有vs受保护 [英] Java OOP Public vs Private vs Protected

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

问题描述

我了解公开,私有和受保护的行为.我知道您应该使用它们来遵守面向对象编程的概念,并且我知道如何在一个程序中使用多个类来实现它们.

I understand what public, private, and protected do. I know that you are supposed to use them to comply with the concept of Object Oriented Programming, and I know how to implement them in a program using multiple classes.

我的问题是:我们为什么要这样做?为什么我不应该让一个类直接修改另一个类的全局变量?而且,即使您不应该这样做,为什么仍然需要保护,私有和公共修饰符?就像程序员不相信自己不这样做一样,即使他们是编写程序的人.

My question is: Why do we do this? Why shouldn't I have one class modifying the global variables of another class directly? And even if you shouldn't why are the protected, private, and public modifiers even necessary? It's as if programmers don't trust themselves not to do it, even though they are the ones writing the program.

谢谢.

推荐答案

您是对的,这是因为我们不能相信自己.可变状态是计算机程序复杂性的一个主要因素,要构建起先看起来还不错的东西,然后随着系统的变大而失去控制,就太容易了.限制访问有助于减少对象状态以不可预测的方式更改的机会.这个想法是让对象通过定义明确的渠道相互通信,而不是直接调整彼此的数据.这样,我们就有希望测试单个对象,并对它们在大型系统中的行为方式充满信心.

You're right, it's because we can't trust ourselves. Mutable state is a major factor in complexity of computer programs, it's too easy to build something that seems ok at first and later grows out of control as the system gets bigger. Restricting access helps to reduce the opportunities for objects' states to change in unpredictable ways. The idea is for objects to communicate with each other through well-defined channels, as opposed to tweaking each others' data directly. That way we have some hope of testing the individual objects and having some confidence in how they'll behave as part of a larger system.

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

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