为什么我们用Java声明私有变量? [英] Why do we declare Private variables in Java?

查看:80
本文介绍了为什么我们用Java声明私有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑,因为我一直听到的是Java中的私有变量应该用来保护代码或变量.但是,如果任何人都可以访问该代码,那么如果它是私有的,则没有什么区别,他们仍然可以对其进行更改.因此,当有权访问该代码的任何人都可以更改它时,如何将其视为受保护的?

I'm confused because all I keep hearing is that private variables in Java are supposed to protect the code or the variable. But if anybody has access to the code, then it makes no difference if it is private, they can still change it. So how is it considered protected when anybody who has access to the code can change it?

推荐答案

当程序员谈论访问变量时,它们的意思是在程序运行时访问其.保护代码免受更改完全是另一回事,需要人工处理,而不是编程语言的语法.在代码运行时,将变量设为私有可保护"其值.在这个级别上,我们不关心保护它不受其他程序员更改代码本身的影响.所谓的数据隐藏"的目的是使内部数据对使用该类的其他类隐藏.其他类只能通过在类上调用方法来访问行为,而不是直接更改变量的值.

When programmers talk about accessing a variable, they mean accessing its value when the program runs. Protecting the code from changes is another matter entirely and requires human processes rather than syntax of a programming language. Making a variable private "protects" its value when the code runs. At this level, we are not concerned with protecting it from other programmers changing the code itself. The point of so-called "data hiding" is to keep internal data hidden from other classes which use the class. Those other classes should only access behavior by calling methods on the class, not by changing values of variables directly.

当程序员编写正确的代码时,遵循诸如数据隐藏"之类的常规编程原则可以帮助我们.如果任何类都可以更改变量的值,则很难确保该值有效.举例来说,您有一个变量,用于计算工厂制造的小部件的数量.通过使变量成为私有数据成员,可以更轻松地确保该值永远不会为负.另一方面,如果该变量是公共变量,则另一个类可以将其更改为负值,这可能导致代码的其他部分崩溃.

General programming principles such as "data hiding" are followed to help us as programmers write correct code. If any class can change a variable's value, then it is difficult to ensure that the value is valid. Say for example, you have a variable which counts the number of widgets a factory manufactures. By making the variable a private data member, you can more easily ensure that the value is never negative. On the other hand, if the variable is public, another class could change it to a negative value which can cause other parts of the code to crash.

这篇关于为什么我们用Java声明私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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