为什么我们在 Java 中声明私有变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48820066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do we declare Private variables in Java
提问by Fido Dido
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.
我很困惑,因为我一直听到的是,Private variables
在 Java 中应该保护代码或变量。但是,如果任何人都可以访问代码,那么它是否是私有的也没有什么区别,他们仍然可以更改它。那么当任何有权访问代码的人都可以更改它时,它如何被认为是受保护的。
回答by Code-Apprentice
When programmers talk about accessing a variable, they mean accessing its valuewhen 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.
遵循诸如“数据隐藏”之类的一般编程原则来帮助我们作为程序员编写正确的代码。如果任何类都可以更改变量的值,则很难确保该值有效。例如,您有一个变量来计算工厂制造的小部件数量。通过使变量成为私有数据成员,您可以更轻松地确保该值永远不会为负。另一方面,如果变量是公共的,另一个类可能会将其更改为负值,这会导致代码的其他部分崩溃。
回答by Ravi
why are variables private in java
为什么变量在java中是私有的
To achieve encapsulation and this can't be accessible outside the class. This doesn't mean programmer can't change the source code.
实现封装,这在 class 之外是无法访问的。这并不意味着程序员不能更改源代码。
回答by Kishor Velayutham
To keep it as simple :
保持简单:
Private variables, are variables that are visible only to the class to which they belong.
私有变量,是仅对它们所属的类可见的变量。
Hope you aware of Encapsulation. It actually binds the object state(fields) and behaviour(methods) together.
希望您了解封装。它实际上将对象状态(字段)和行为(方法)绑定在一起。
How to implement encapsulation
in java:
encapsulation
在java中如何实现:
1) *Make the instance variables private*
so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class.
1)*Make the instance variables private*
使它们不能从类外直接访问。您只能通过类的方法设置和获取这些变量的值。
2) Have getter and setter methods in the class to set and get the values of the fields.
2) 类中有 getter 和 setter 方法来设置和获取字段的值。
Let me give you one real time example for the better understanding.
让我给你一个实时的例子,以便更好地理解。
public class bank_balance
{
public String owner;
public int balance;
public bank_balance( String name, int dollars )
{
owner = name;
if (dollars >= 0)
balance = dollars;
else
dollars =0;
}
}
We have declared our string and integer to be public. This means that any object in the system can change the balance (setting it to zero, or even giving us a negative balance). This could cause the program to fall over, even though we wrote code in our constructor to prevent negative balances.
我们已经声明我们的字符串和整数是公开的。这意味着系统中的任何对象都可以改变余额(将其设置为零,甚至给我们一个负余额)。这可能会导致程序崩溃,即使我们在构造函数中编写了代码以防止出现负余额。
Instead, we should have provided a getBalance/setBalance method, and made our balance private or proteced. Other objects can still access the data, but they can't put invalid data in.
相反,我们应该提供一个 getBalance/setBalance 方法,并使我们的余额私有或受保护。其他对象仍然可以访问数据,但不能放入无效数据。
public class bank_balance
{
public String owner;
private int balance;
public bank_balance( String name, int dollars )
{
owner = name;
if (dollars >= 0)
balance = dollars;
else
dollars =0;
}
public int getBalance()
{
return balance;
}
public void setBalance(int dollars)
{
if (dollars >= 0)
balance = dollars;
else
dollars = 0;
}
}
Hope this helps..!
希望这可以帮助..!
回答by Ari Singh
"Private" variable means "controlled" access not "no" access. e.g. I can make the variable read-only by having only a getter method and no setter method. The owning class decides the access to to be provided to the variable - via methods it exposes to the public.
“私有”变量意味着“受控”访问而不是“无”访问。例如,我可以通过只有一个 getter 方法而没有 setter 方法来使变量只读。拥有的类决定提供给变量的访问权限——通过它向公众公开的方法。
Also I can validate the value before storing it and reject values that are not allowed. I can also log the changes to the value.
此外,我可以在存储之前验证该值并拒绝不允许的值。我还可以记录对值的更改。
It can also synchronize multiple variables so that it can be all in a consistent state e.g. doing debits and credits simultaneously.
它还可以同步多个变量,使其处于一致状态,例如同时进行借方和贷方。
And no - other people cannot change my code e.g if I provide my code as a compiled "jar" file. Or if they change it, and they break it - they own it (i.e. be responsible for the consequences their code change does).
不 - 其他人无法更改我的代码,例如,如果我将我的代码作为已编译的“jar”文件提供。或者,如果他们更改了它,并且破坏了它——他们拥有它(即对他们的代码更改造成的后果负责)。
An analogy from a real life would be room mates sharing expenses thru a shared wallet. If the wallet is public - anyone can take money from the wallet - no accountability. But let's say one of the room mates (owning class) owns the wallet (private variable) - and provides a "getter" (you ask for money and I will give you from the shared wallet) to access the wallet - there is more accountability. No more anyone taking the money from the wallet will nilly. The keeper of the wallet can then log all access to it - in case of bugs (disputes) - to troubleshoot the problem. Similarly "addToWallet" method (room mates contributing to the wallet) can be used to add money to the wallet - again with more accountability as opposed to wallet lying in the open with any of the room mates adding / removing money from it willy nilly.
现实生活中的一个类比是室友通过共享钱包分担费用。如果钱包是公开的——任何人都可以从钱包里取钱——没有责任。但是假设其中一个室友(拥有班级)拥有钱包(私有变量)——并提供一个“getter”(你要钱,我会从共享钱包中给你)来访问钱包——有更多的责任. 再也没有人从钱包里拿钱了。然后,钱包的管理员可以记录对它的所有访问 - 在出现错误(争议)的情况下 - 以解决问题。类似地,“addToWallet”方法(室友为钱包做贡献)可用于向钱包添加钱 - 再次具有更多的责任感,而不是任何室友随意添加/移除钱的钱包。
回答by Anthony
Public = accesible with other Class
公共 = 其他类可访问
Private = not accesible with other Class
私有 = 其他类不可访问
So if you have a private variable, it will not be accesible with other Class
因此,如果您有一个私有变量,则其他类将无法访问它
回答by Riaan Nel
Variables are private to protect the state of your objects - in object-oriented programming terms, this is called encapsulation.
变量是私有的,用于保护对象的状态——在面向对象的编程术语中,这称为封装。
Here's a very simple example. Imagine that we have a Person class, and a Person has an age that is calculated based on the year in which they were born.
这是一个非常简单的例子。想象一下,我们有一个 Person 类,一个 Person 的年龄是根据他们出生的年份计算的。
class Person {
private int yearOfBirth;
private int age;
public Person(int yearOfBirth) {
this.yearOfBirth = yearOfBirth;
this.age = Calendar.getInstance().get(Calendar.YEAR) - yearOfBirth;
}
public int getAge() {
return age;
}
}
In another class somewhere, we have this... and if age was public, we could really mess up the state of our object by changing it without updating the year of birth.
在某个地方的另一个类中,我们有这个……如果年龄是公开的,我们真的可以通过更改对象的状态而不更新出生年份来弄乱对象的状态。
public static void main(String[] args) {
Person bob = new Person(2000);
System.out.println("Bob's age: " + bob.getAge());
bob.age = 100; //This would be BAD!
}
By encapsulating the age variable, it's safe from unexpected changes and our class can manage its own state. Anyone who uses our class doesn't have to care about calculating a person's age, because that's encapsulated within our class.
通过封装 age 变量,可以避免意外变化,我们的类可以管理自己的状态。任何使用我们类的人都不必关心计算一个人的年龄,因为它封装在我们的类中。
回答by Jayanth
Data Hiding/Encapsulation:
数据隐藏/封装:
Data hiding is not same as Abstraction. Not to confuse one with the other.
数据隐藏与抽象不同。不要将一个与另一个混淆。
Abstraction is hiding the code implementation from other Object/user whereas Data hiding is achieved by Encapsulation via POJO classes.
Data hiding has to do with the instance variables which decides the state of the Object. Hiding its content using the setter() and Getter() methods is Data Hiding/ Encapsulation.
抽象是对其他对象/用户隐藏代码实现,而数据隐藏是通过 POJO 类的封装实现的。
数据隐藏与决定对象状态的实例变量有关。使用 setter() 和 Getter() 方法隐藏其内容是数据隐藏/封装。
You may wonder, how a getter() method is hiding the data whereas it just returns the data we requested but there is an untold story about the getter/setter methods.
您可能想知道 getter() 方法如何隐藏数据,而它只返回我们请求的数据,但关于 getter/setter 方法有一个不为人知的故事。
Example:Refer the getName() method from the below code
示例:参考以下代码中的 getName() 方法
public class Person {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
// can restrict the code without displaying data to user
if(condition)//restricted user check
return null;//returning null because the user is not supposed to view the data
return name;
}
}
This can only be possible if the access modifier is private because if they are public or other we can directly access them through the object. If it is private, only then you have the ability to restrict your code.
这只有在访问修饰符是私有的情况下才有可能,因为如果它们是公共的或其他的,我们可以通过对象直接访问它们。如果它是私有的,则只有这样您才能限制您的代码。