Prabath Hewasundara
Prabath Hewasundara

Reputation: 111

Java setter and getter methods

When I am using setter and getter methods, can I use any method name instead of getVariable/setVariable?

In fact can I use

public void abc(String name){
    this.name=name;
}

Instead of

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

Upvotes: 0

Views: 291

Answers (4)

persistent_poltergeist
persistent_poltergeist

Reputation: 564

It is a naming convention that is followed by the programmers to name the getters and setters as getName() and setName(). In normal Java programs even if you don't perform this convention it is not going to cause a problem other than readability(which is of utmost importance). But when you start using frameworks in java, for example the Spring Framework usually searches for getters and setters with the naming conventions getName() and setName() manipulate an object. so it is better to use this naming convention.

Upvotes: 3

Hamza Riaz
Hamza Riaz

Reputation: 21

Yes you can use use any name with the methods. the main concern is to call the method as object.method(); This is just a naming convention for ease of readability.. It might cause a problem with the frameworks because of pre-defined things in libraries..

Upvotes: 0

Ashish Ani
Ashish Ani

Reputation: 332

Yes, You can give any valid name to a method in Java to get or set values of a member variable. But a getter method is used to get the value of member variable of a Class and setter method is used to set values of member variables of a class. So, Its a convention or Java Coding standard to use getX()/setX(), where X is a field variable name. Basically to increase readability and maintenance, these types of convention or standards are used.

Upvotes: 0

Piper Anderson
Piper Anderson

Reputation: 41

According to Java convention, a getter has a getProperty (or isProperty in case of boolean type), and a setter has a setProperty for private fields. You don't have to follow this, but it is recommended since some tools are expecting this convention.

Upvotes: 2

Related Questions