Re: Accessor Methods
fightingbull06@yahoo.com wrote:
Am a newbie to Java Programming and am studying Accessor Methods.
If you designate variables as "private", then you can change their
values using "accessor methods". So what's the point of making them
"private" if you can still manipulate them using accessor methods.
Two reasons:
1. It is a matter of coding style. Allowing direct manipulation of
member variables would violate the principles of Object Oriented
Programming (OOP). Generally only constants (public static members) used
by accessors of the class should be accessible from outside of the
class. (I mean things like the BorderLayout.SOUTH constant used to tell
a BorderLayout instance you want to place a component in its south pane.)
2. You can perform validity checks on the new values given through
accessor methods. This can't be done if the member variable is
accessible from outside of the class. Let's say you have a class called Dog:
public class Dog{
int age;
public void setAge(int a){
if(a>=0){
this.age=a;
}
else{
throw new IllegalArgumentException("Age cannot be negative.");
}
}
}
Now, if you don't declare the variable "age" private, you (or someone
else using the Dog class without knowing anything about its inner
workings) could do something like:
Dog rufie = new Dog();
rufie.age = -3; //does not check for validity
instead of
rufie.setAge(-3); //throws IllegalArgumentException
Somewhere later on, this weird Dog with a negative age could cause some
unforeseen trouble.
--
-Aki Laukkanen