I would like to find a tutorial that explains when and why to use various modifiers. for example when/why might i want to declare a variable public int a; I can understand making a Static variable public. But I'm unsure when to use which modifiers. most of my code ive written doesnt have static anything. i make all member variables private unless i see a problem. its one thing knowing what the modifiers do its another knowing when to use which.
Hi Randall, I don't know of any tutorial on this question, but I'll try to answer shortly of my own experience on this. When you design a class, most of the time as you said, you will specify the member variables access as private, so that they are hidden to the "clients" of your class, and use getters and setters to set or get the value. This is encapsulation and it is applicable on the majority of classes. It also allows you to perform validation on the setters. However for perfomance reasons or to simplify the use of a small class, instead of using this method, specifying the member variable as public would be preferred. But this can only be done when no validation is required or when the class in question doesn't have to be exposed as a Java Bean. Let's take an example. Let's say you have to design a application that will display color spheres in a 3D space. The requirements specifies that a sphere can be specified with 3 coordinates, a radius and a color. No validation is needed on the coordinates. On the other end, the application is required to perform simple validation on the radius (i.e. positive only). To offer a better performance for this application, it seems appropriate to offer public access for the x,y,z coordinates and color variables, and private access to the radius.
You will then be able to build an array of Colored spheres and send this array to a 3D rendering engine that may allow the user to navigate through this virtual world. Hope this helps, Beno�t