Java Reference
In-Depth Information
it is not accessible from outside the class. In other cases you must make your method ac-
cessible from outside. The same is true about the variables you create. It is easier to un-
derstand when to set accessibility level of variables. So first let us understand accessibility
level of variables and then we will think the same about methods.
In figure 1.9 you can see that we have created variables at class level as well as inside
methods. Class level variables can be both public as well as private. These variables are
also known as class variables. If they are public then they can be accessed from outside the
class. If they are private then they can be accessed from within the class only. This access-
ibility level has profound effects. If any variable is declared public at class level then it can
be modified by any class. This will lead to bad coding as it may allow defects to creep in
through this free calling from any class. So these variables should be private. But if they
are private then what is the use of declaring them at class level? If you think about it then
it is one of the fundamental principles of object oriented programming. It is known as en-
capsulation. We will learn about encapsulation in the section for classes.
It is still possible to use these variables (even if they are private) from outside. It is done
through using get and set methods. This way, the variables are not directly accessible from
outside and yet they can read or assigned values from outside in a round about way using
get and set methods. The beauty is that you have total control whether the values need to
be read only or any values to be assigned to them.
Now coming to methods, most computations which need to be done locally should be done
inside private methods. There is no need to make them public. On the other hand a type
of method which is known as constructor is always declared as a public method. Here the
name of the method is same as the name of the class. it is known as the constructor method.
Search WWH ::

Custom Search