• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessor (set) / Mutator (get) Methods

 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I've been looking at a better understanding of the set/get methods. So far I have come up with the following. Could anyone confirm whether my understanding is correct and if not elaborate more.

Thank you.

accessor methods
Normally you don't make variables in your class public. Instead you provide public set and get methods for the variable. This lets you then later change the way the variable is stored, or add extra validation checks.

Method names made up of a member name with a get or set prefix are methods that are required because the members are private and therefore cannot be accessed from outside the class. Any program that creates instances of a class will use these methods to access the members. A member does not need a set method when its value is changed in other methods.

The get/set methods are not compulsory, only include them for members when other classes require access to them.

The get methods (also called an accessor method) return the value of the member they are associated with and the set method (also called a mutator method) sets the member to a new value.

Using get and set methods aids maintainability, flexibility and extensibility. Good design includes encapsulation � to do this you make public accessor methods and force calling code to use those methods. i.e. set and get
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yep, Maureen, you sounds like you have a good understanding of the getters & setters.

If you want your POJOs to be readonly, do not provide any setters. Similarly for variables that you do not wish to be modified by others directly, do not provide a setter for it. As you had mentioned, this variable's value could be computed from other values, & by not providing a setter, you don't risk it being changed by others.

As for the validation checking, this is usually not done inside the getter/setter methods. You could do these validation checkings before calling these methods.

Cheers
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One more thing: Java beans expect the naming convention getXxx() setXxx() to be followed.
 
Hentay Duke
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you think of some examples when getter/setters are useful? Can you explain why encapsulation is important? If so then you have a good understanding.

BTW, did you come up with your explanation of them yourself? Because your post reads like something out of a text book.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic