We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › public & private
Page Index Toggle Pages: 1
public & private (Read 720 times)
public & private
Jan 4th, 2010, 1:46pm
 
Ok so when you're working in Java you have to declare stuff private or public, and if it's private you gotta do certain things to access it.

Why not just make everything public?
Re: public & private
Reply #1 - Jan 4th, 2010, 2:00pm
 
As programs grow complexer, it is nice to know what can and what cannot be accessed from certain places (this usually limits the time needed to change/understand code).

Also, with private members/methods you control what the "user" of the class can do with the class.
Re: public & private
Reply #2 - Jan 4th, 2010, 3:18pm
 
cool thanks!
Re: public & private
Reply #3 - Jan 5th, 2010, 5:02am
 
Let's take a class doing some stuff.
You create a public API, ie. a set of functions (methods) to allow setting some parameters, and to get the result.
You can see it as a black box, with plugs to pour things in and to pull things out.
The way the class works isn't important for the user of the class.
So if it uses some intermediary variables, they shouldn't be visible from the outside: users must not alter these variables, and they are distracting when studying the API (as JR said).
Moreover, one can find a better way to do the job, and thus add, remove or change these variables. But the external API doesn't change.

That's also why in most Java libraries, you don't access the fields (the public variables) directly, but through accessors, ie. setters and getters (like getFontSize(), setBackgroundColor()).
Moreover, it insulates the user from the way of storing data: they doesn't have to know if we store color as an int or as three or four fields, in HSB or RBG, in ints or floats, etc.
And we can add checking on the validity of data: in setItemNumber(), you can throw an exception if the number is negative. Or silently convert it to zero or its absolute value. Etc.

Of course, most of these remarks are more useful for work in teams, on large projects, or to make libraries to be shared. Most Processing sketches are OK with public or default access.
Page Index Toggle Pages: 1