Im learning java, coming from python there are quite a few things I don't fully understand that exist in java and the first of these has to be public and private declarations. I mean from a language that has no real visible public private declarations to a language where everything MUST be private, I understand the ground principle about what they do. Im asking 'why' they do it. Why should anyone care who touches there private parts? It shouldn't really be a problem if your a good programmer you know which bits you 'should' and 'should not' poke in code. So why the secrecy? Why hide and obscure and make things private from the world? Why care to start with.
-
Don't quote me http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – Jakob Bowyer Jul 12 '11 at 10:06
-
6+1 for worrying about the "private parts" being touched. I share that concern every day! :D – Lukas Eder Jul 12 '11 at 10:07
-
so that no one can touch them... – Denis Tulskiy Jul 12 '11 at 10:07
-
4I asked this question in the ##java channel on irc and someone said, "would you let anyone touch your private parts?" to which my answer was, "yes." – Jakob Bowyer Jul 12 '11 at 10:07
-
@tulskiy that is not an answer! that is paranoia! – Jakob Bowyer Jul 12 '11 at 10:08
-
at least embed a trollface picture into the question, or is that a serious question? – Denis Tulskiy Jul 12 '11 at 10:09
-
1"... if your a good programmer you know which bits you 'should' and 'should not' poke in code..." - yes but there are people who are not good programmers who don't know. I guess one thing is it helps people to work out what should and shouldn't be touched. – luketorjussen Jul 12 '11 at 10:10
-
3@Jakob: What's the largest program/library you've ever written? On a team of how many people? Yes. Immediately the answer becomes obvious why it's good to `encapsulate` things: http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 – Lukas Eder Jul 12 '11 at 10:11
-
I haven't ever really written anything major myself Im only 17, but I have seen projects like Twisted, it doesn't really rely on encapsulation to achieve great results. – Jakob Bowyer Jul 12 '11 at 10:12
-
@tulskiy, this is a serious question. I just don't get why people NEED the distinction between public and private. – Jakob Bowyer Jul 12 '11 at 10:12
-
2It's not a bad question, and it's a good sign that you think about it. Encapsulation is a great concept. You should read about it. – Lukas Eder Jul 12 '11 at 10:13
-
That isn't the point! Try to stay on topic. – Jakob Bowyer Jul 12 '11 at 10:16
-
It does make your doco cleaner. Imagine if you had all kinds of help methods in your auto-generated documentation. – Ankur Jul 12 '11 at 10:16
-
I can see that being an advantage granted, but why limit access in favour of documentation. – Jakob Bowyer Jul 12 '11 at 10:18
-
@Jakob, it's the *hidden* topic! – Lukas Eder Jul 12 '11 at 10:18
-
I love how any question that gets OTHER people fired up gets flagged to close. – Jakob Bowyer Jul 12 '11 at 10:30
-
2@Jakob Very few gets fired up about facts, and Stack Overflow is here to *provide answers*, not to be a *discussion platform*. People usually only gets fired up when they have a chance to discuss. Your question is asking for an opinion, not for a fact, and hence why people are fired up, as well as why it was closed. – Lasse V. Karlsen Jul 12 '11 at 11:40
-
I would say the answer to this question is so you can have confidence to make changes to the internal implementation of your library without worrying that you are going to break everything that uses that library. Otherwise people may not even realize that the feature wasn't intended to be publicly accessible, and you could end up having to continue supporting the old API even though it wasn't public. For a real life example, see https://code.djangoproject.com/ticket/17085 – Penguin Brian Jan 15 '16 at 23:43
9 Answers
(Opinionated answer follows.)
This is because Java is a bondage and discipline language, designed to cater for mediocre programmers. Python, otoh, is a language aimed at consenting adults who agree to expose their objects' private parts to each other, trusting other programmers not to abuse the undocumented/unguaranteed functionality offered to them. If they do and anything breaks, the person who broke stuff gets to keep the pieces.
Python does have some access control, such as __all__
to hide/show parts of a module, it's just that all of it is optional and can be by-passed at the risk of the person doing so.
(To repeat what I said in the comment: I'm not saying that all Java programmers are mediocre. I'm just saying that the language is designed so that it can safely be used by such programmers.)
-
1Wow. "aimed at mediocre programmers". I wonder what Josh Bloch thinks about this... – Lukas Eder Jul 12 '11 at 10:16
-
I'm not saying that all Java programmers are mediocre ones, and neither does Joel Spolsky in the linked article. I am saying, however, that Java is designed to accomodate such programmers' flaws. Or, that it protects the good programmers from the mediocre ones, but restricts the formers' freedom in the process. – Fred Foo Jul 12 '11 at 10:19
-
1Both languages can be (ab)used by mediocre programmers. Im talking about concepts not opinion. – Jakob Bowyer Jul 12 '11 at 10:19
-
5@Jakob Bowyer: this is a direct answer to your question "*why* should anyone care who touches there private parts", taking into account your "'should' and 'should not' poke in code" remark. The reasoning behind modern programming language design is grounded less in the theory of computation than in programmer psychology and the economics of the IT sector. – Fred Foo Jul 12 '11 at 10:24
-
@larsmans: Nicely put. I had never thought about computation-theory vs. programmer psychology. But it's very true... – Lukas Eder Jul 12 '11 at 10:27
Because others people don't care nearly as much about your privates as you do. You decide what is and isn't private.
On a serious note, public things define the API - the contract with the outside world - it's an important decision to make. On the other hand, as much stuff as possible should be private - that's encapsulation. Welcome to OO.

- 412,405
- 93
- 575
- 722
You don't want other programmers accessing and possibly modifying your private variables. e.g.
private int ryan; //its your responsibility to save private ryan
All jokes aside, privates are useful for encapsulation. Plus, private constructors disallow subclassing and feature in the factory method pattern. Classes with private constructors only allow objects to be instantiated within this class (which can be done via a static public method for example).
So as you can see, privates can be quite useful....

- 9,102
- 5
- 39
- 43
This principle of hiding data members is known as Data Encapsulation.
From the article above:
The advantage of using data encapsulation comes when the implementation of the class changes but the interface remains the same. For example, to create a stack class which can contain integers, the designer may choose to implement it with an array, which is hidden from the user of the class. The designer then writes the push() and pop() methods which puts integers into the array and removes them from the array respectively. These methods are made accessible to the user. Should an attempt be made by the user to access the array directly, a compile time error will result. Now, should the designer decide to change the stack's implementation to a linked list, the array can simply be replaced with a linked list and the push() and pop() methods rewritten so that they manipulate the linked list instead of the array. The code which the user has written to manipulate the stack is still valid because it was not given direct access to the array to begin with.

- 13,351
- 8
- 59
- 84
-
Why not just let people play with the array or linked list in the first place? Then you don't NEED the `push` and `pop` methods although I can agree it would be nicer to have them. – Jakob Bowyer Jul 12 '11 at 10:14
-
1It is specifically the push and pop, which makes a Stack a Stack. So essentially when I see a `Stack`, I know it is a LIFO data structure, and can focus on my application, without caring about reinventing the wheel (Stack) – Ozair Kafray Jul 12 '11 at 10:19
-
Surely arrays in java support pop and append (or what ever it is called) so you don't need to create an object around them? – Jakob Bowyer Jul 12 '11 at 10:22
-
I don't think arrays in Java support that. Even if they do, this is an example, you can take the example of a circular queue. You can implement it using arrays, linked lists etc. But, I guess what you are talking about is self-responsibility. – Ozair Kafray Jul 12 '11 at 10:31
You are free to declare every field in your class as public. Why this is not considered "good practice" is because in a multi-developer situation, where a codebase has to be maintainable over time (and after you leave), it is important for other people to be able to understand your classes (and how they should and should not be used). Making a field "private" is an excellent way to forcible indicate that this field is internal to the workings of the class and should not be modified from the outside. It's not about "obscuring", it's about "securing" and "maintaining" (see above posts about API and contract).
Sure, a "good programmer" would be able to eventually figure out the exact workings of your code, given enough time - but why would you not spare him or her that time by instead making the effort of only exposing the "public" functionality (the API) and hiding the stuff that should not be touched?
On a side-note, and purely for your benefit, not practicing proper data encapsulation and API/public interface discipline will make your peers detest you and will most likely get you fired, in short order. The code you produce will be regarded (rightly) as very brittle and unmaintainable.

- 27,064
- 6
- 41
- 46
Take this example of why you might want to prevent other programmers, or even yourself, from using a variable directly.
class Car() {
public int speed;
}
You, or another programmer, might just do "speed = -20" (perhaps because a calculation was wrong or another function isn't acting as expecting). Then when you try to use your speed, you get weird results and spend time and energy tracking down the problem. This is a better solution:
class Car() {
private int speed;
public void setSpeed(int newSpeed) {
if (newSpeed < 0)
throw new Exception("Car speeds can't be negative!");
speed = newSpeed;
}
public int getSpeed() {
return speed;
}
}
You will know right away if your interface is used as you don't intend.
Your question indicates that you might be a little confused about why public and private methods are even useful, so let's take a step back.
You don't declare "everything" private. You declare things private when you do not want other classes using them -- they are totally for internal use. You declare things public when use of your class requires calling that method or using that variable. Indeed, a class with no public methods wouldn't be that useful! (this statement is a pure lie but it works for what we're talking about.)
By making the things you intend to be used from outside the class public and everything else private, you are creating an interface for people using your classes -- either you or others. The heavy lifting is hidden from every other class.
In one sentence: "Program to an interface, not an implementation." When you write a class, the first thought should be "How do I intend other classes to use my class?", not "How should I get the functionality I want?" In my opinion, that distinction is the difference between the mindsets you should have when doing imperative programming and object oriented programming.

- 5,365
- 14
- 51
- 80
well it is really easy to understand the need for private modifiers in java which is purely an object oriented language
consider you have a very nice sports car A!
would you like to have a field called gasPumped and maybe some other fields that may increase the speed?
or
would you like to have a function called increaseSpeed() which access all these fields?
Probably when you get the new version of this car, it will have the same increaseSpeed() with much more fields that are manipulated!
The car manufacturer wants you to know that you can
increaseSpeed()
but he doesnt really want you to know the inside parts!

- 45,786
- 16
- 89
- 106
I would say that privates are private in Java because:
- the mechanism is inherited from C++ (in C++, having all fields/methods be accessible by clients would mean putting them in the header file, which would put a significant and undue burden on the clients)
- it allows for some static optimizations that are otherwise impossible (e.g. you can inline a private method call - effectively removing the method from the compiled class, while still keeping your source code structured).

- 16,518
- 5
- 56
- 90
- It simplifies the API to keep implementation dependent stuff private.
- Good object oriented design demands that each class has its own scope of functionality. Hence its a good thing to keep others from violating this by accessing such fields or implementation dependent methods directly.
- Classes are easier to maintain this way. For example changing the internal data structure doesn't affect others which would be the case when they accessed the fields directly.
- Other people can't mess up the object's state.

- 3,156
- 3
- 26
- 36