Why do we declare Private variables in Java

2020-03-30 05:09发布

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.

7条回答
迷人小祖宗
2楼-- · 2020-03-30 05:36

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.

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.

Example: Refer the getName() method from the below code

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.

查看更多
\"骚年 ilove
3楼-- · 2020-03-30 05:41

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.

查看更多
我想做一个坏孩纸
4楼-- · 2020-03-30 05:42

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

查看更多
Luminary・发光体
5楼-- · 2020-03-30 05:44

"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.

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).

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.

查看更多
smile是对你的礼貌
6楼-- · 2020-03-30 05:46

why are variables private in java

To achieve encapsulation and this can't be accessible outside the class. This doesn't mean programmer can't change the source code.

查看更多
孤傲高冷的网名
7楼-- · 2020-03-30 05:50

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:

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.

2) Have getter and setter methods in the class to set and get the values of the fields.

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.

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..!

查看更多
登录 后发表回答