Link to home
Start Free TrialLog in
Avatar of jaggybala2
jaggybala2

asked on

Why Getter and Setter methods?

Could you please tell me why we use Getter and Setter methods in Java ?
Avatar of zzynx
zzynx
Flag of Belgium image

1) It's "cleaner" not to mess with the data members directly.
2) Maintenance

    public int getWhatever() {
        return whatever1;
    }


    If that should ever change in

    public int getWhatever() {
        return whatever1 * whatever2;
    }

    You have to change it only here. Every place where getWhatever() is used can stay as it is.

    That's not the case if you would have used

             instance.whatever1;        ==>   instance.whatever1 * instance.whatever2;
I mainly use them in two cases

a) when I want to wrap some value around and I do not want to break the existing code
b) when I want to access variables from inner classes and the calling would be "ugly", I just have an accessor that does the job for me.

Apart from that no special reason. Besides if you do not use them you reduce the code of the programme.
ASKER CERTIFIED SOLUTION
Avatar of sciuriware
sciuriware

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sciuriware
sciuriware

P.S.: all encapsulated constructs, like classes, activexes, beans and the sort are subjected
to obligatory getter and setter - access.
As a side-effect, you can construct access to a field at runtime if you know the name of the class and the field
and if the programmer kept to the standard that field xyz has getXyz() and setXyz().
(that's a plug-in!)
;JOOP!
Avatar of jaggybala2

ASKER

now, i am much confused of whom to give the points. O:-)
You should award the points to the comment you value most, i.e. to the comment you think it provided the best answer. If you value all comments the same a good practice is to award the points to the first one who answered your question.

Another thing you can do (if you have points available) is to increase the number of points and do a split between all the participants (minimum of 20 points each).
i go with sciuriware as his explanation is *much* understandable for me. I hope other experts dont get angry. afterall, i have very less points.
Not at all, glad you are helped :)
jaggybala2, we're not exclusively here for the points; we learn too.
And I mostly appreciate your comment.
Before all I want to improve the quality of my explanations.

;JOOP!