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
-~----------~----~----~----~------~----~------~--~---

Reply via email to