Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the use of private keyword

Tags:

I am new to programming. I am learning Java now, there is something I am not really sure, that the use of private. Why programmer set the variable as private then write , getter and setter to access it. Why not put everything in public since we use it anyway.

public class BadOO {
    public int size;

    public int weight;
    ...
}

public class ExploitBadOO {
    public static void main (String [] args) {
        BadOO b = new BadOO();
        b.size = -5; // Legal but bad!!
    }
}

I found some code like this, and i saw the comment legal but bad. I don't understand why, please explain me.

like image 310
LAT Avatar asked Jun 02 '10 03:06

LAT


1 Answers

The most important reason is to hide the internal implementation details of your class. If you prevent programmers from relying on those details, you can safely modify the implementation without worrying that you will break existing code that uses the class.

So by declaring the field private you prevent a user from accessing the variable directly. By providing gettters and setters you control exactly how a user may control the variable.

like image 62
Martin Avatar answered Oct 19 '22 22:10

Martin