Monday, January 6, 2025
HomeProgrammingAccessor and Mutator in Java

Accessor and Mutator in Java

Accessors (Getters):

  • Retrieve the value of a private field.
  • Named as getFieldName.
java
public String getName() {
return name;
}

Mutators (Setters):

  • Modify the value of a private field.
  • Named as setFieldName.
java
public void setName(String name) {
this.name = name;
}

Example:

java
public class Person {
private String name;

public String getName() { return name; }
public void setName(String name) { this.name = name; }
}

Benefits:

  • Encapsulation and controlled access.
  • Allows validation in setters.
  • Follows JavaBean conventions.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x