Hi, in practice what i faced is that you'd better use access to variables
through methods because -
One reason for this i think (setters and getters usage) could be some
validation tasks, if you will access fields directly it might cause some
problems ....
int _grade;
...
private void setGrade(int grade){
if (grade != 0 || grade <= 10 || grade > 0){
this._grade = grade;
}
else {
// throw_new_grade_setting_exeption;
}
}
Another reason could be class organization for persistence.
and, as it was said before, because of encapsulation....
2009/1/21 BillyRay <[email protected]>
>
> I've noticed that sometimes getter/setter methods are used inside of a
> class to access instance variables while other times the variables are
> accessed directly. For example, within constructors, instance
> variables often appear to be access directly:
>
> public MyClass( String name ) {
> this.name = name;
> }
>
> instead of using the setter method:
>
> public MyClass( String name ) {
> setName( name );
> }
>
> (Obviously, all setter methods must necessarily access the variable
> directly.)
>
> However, In other instance methods the getter/setter methods are used
> instead of the variables themselves. For example, the method used to
> calculate the average grade in the student record example used the
> getter methods to access the instance variables for each of the three
> grades:
>
> public double getAverage() {
> double avgGrade = ( getEnglishGrade() + getMathGrade() +
> getScienceGrade() ) / 3;
> return avgGrade;
> }
>
> rather than accessing the instance variables directly as in:
>
> public double getAverage() {
> double avgGrade = ( englishGrade + mathGrade + scienceGrade ) / 3;
> return avgGrade;
> }
>
> What are the rules or guidelines for deciding when it is appropriate
> to use the getter/setter methods to access instance variables in
> another method inside of a class versus accessing the variables
> directly?
>
> Thanks!
>
> BillyRay
>
> >
>
--
С уважением, Николай.
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---