Java is known for its object-oriented programming, which allows attributes/values to be stored and manipulated within an object. The getter and setter methods play a critical role in accessing and modifying object attributes. They are essential modules in Java, that make it possible to maintain the security and integrity of objects, particularly when you’re working on a large-scale enterprise project. In this article, we’ll examine the definition of getter and setter methods, when to use them, and some code examples to illustrate how they can be used in your Java program.
Getter Methods
Getter methods are used to access and retrieve the value of an instance variable or attribute of objects defined in a class. A getter method is a standard module that retrieves the value of a private field or data variable and returns it as the method’s output. The method declaration is as follows:
public data_type getVariable_name(){
// Method logic
return variable_name;
}
- The
public
keyword indicates that the getter method is accessible to other classes. - The
data_type
is the data type of the value being returned (e.g., int, string, double etc.) - The name of the getter method must begin with the keyword
get
to make it easier to identify. - The
variable_name
represents the object attribute whose value is to be retrieved.
For instance, suppose we have a class called Person
that has an attribute name
, we could retrieve its value using a getter method as follows:
public class Person {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
In the code snippet above, we created a Person
class with a private field, name
. We then created a getter method called getName()
to retrieve the name
value of a particular instance of the class. The method accesses the private field name
and returns its value as a string.
Setter Methods
Setter methods allow the modification of an object’s instance variable or attribute. A setter method is a standard module that accepts a value parameter and then assigns it to its associated object attribute. Setter methods are used to maintain encapsulation, as they allow controlled changes to the object attributes. The method declaration is as follows:
public void setVariable_name(data_type variable_name){
// Method logic
this.variable_name = variable_name;
}
- The
public
keyword indicates that the method can be accessed by other classes. - The
void
keyword signifies that the method does not return a value. - The name of the set method must start with the keyword
set
to identify it easily. - The
data_type
is the data type of the input value to be assigned to the object attribute. - The
variable_name
parameter represents the object attribute that is being set.
For instance, suppose we have a class called Employee
that has an attribute salary
, we could modify its value using the setter method as follows:
public class Employee {
private double salary;
public double getSalary() {
return this.salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
In the code snippet above, we created an Employee
class with a private field salary
. We then created a setter method called setSalary()
to assign a new value to the salary
object attribute. The method takes a double parameter representing the new salary and then assigns it to the salary
object attribute using the this
keyword.
Why Use Getter and Setter Methods?
Getter and setter methods have become standard practice when defining attributes of objects in Java because they offer several advantages, including:
-
Encapsulation – The object’s internal implementation is hidden from external users. This way, the object data and behavior are protected, making it difficult to break the system by unintended interference.
-
Controlled Access – Getter and setter methods provide a degree of control over the data accessed/modified within an object. The user cannot directly access or set the attribute values without the use of getter and setter methods, giving the classes/user control over how the object should be used.
-
Flexibility – Separating the object attributes from their accessors/mutators allow the programmer to change the internal data representation without rewriting the whole code. Additionally, the method implementation can be changed or updated without affecting the user programs.
-
Data Validation – With setter methods, the programmer can implement simple checks on the input value before assigning it to an object attribute. This ensures that the data stored in the object is correct and reliable.
In conclusion, getters and setters are essential building blocks in Java programs. They offer data protection and control of data access, improving the overall design and maintainability of the program. With these methods, Java developers can create robust and secure code systems that can scale easily.
Let's delve deeper into the topics we've discussed about getter and setter methods in Java.
Getter and Setter Conventions
There are some conventions to follow while creating getter and setter methods in Java:
-
The name of the getter method should follow the syntax “getVariableName()”.
For example, if the attribute is firstName, the getter method should be getFirstName(). -
The name of the setter method should follow the syntax “setVariableName(dataType variableName)”.
For example, if the attribute is firstName, the setter method should be setFirstName(String firstName). -
The scope of setter and getter methods should always be public.
-
The data type of the variable in the getter method should match with the data type of the variable in the attribute or the instance variable.
-
Similarly, the data type of the value parameter in the setter method should correspond to the data type of the instance variable.
-
The setter method should always have a void return type.
-
Getter methods should only return the value of the object attribute and should not modify the object in any way.
-
Setter methods should only assign the value to the object attribute and not return any values.
Why Use Encapsulation Techniques?
Encapsulation is an important concept in object-oriented programming. It allows the attributes of an object to be hidden and accessed only through the methods defined in the class. This ensures that the data is properly protected and secure from unauthorized access. Encapsulation is achieved through the use of access modifiers such as private, public, and protected.
Encapsulation prevents users from accidentally altering the internal state of the object using illegal or incorrect input values. This helps maintain data integrity and program stability. It also allows you to change the internal implementation of your classes without affecting the program’s external interface, as we discussed earlier.
Code Examples
Now, let's look at some examples of how to use getter and setter methods in Java classes.
Example 1:
public class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
In the code above, we created a class called BankAccount that represents a simple bank account. The class has a private attribute called balance, which is inaccessible from outside the class. We created a getter method called getBalance() that accesses the balance attribute and returns its value. We also created a setter method called setBalance() that modifies the balance attribute when invoked.
Example 2:
public class Employee {
private String name;
private int age;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
In the code above, we created a class called Employee. The class has three private attributes called name, age, and salary. We created three getter methods that return respective attributes – getName(), getAge(), and getSalary(). Similarly, we created three setter methods for each attribute – setName(String name), setAge(int age), and setSalary(double salary).
Conclusion
Getter and setter methods are useful in setting and getting the attributes of objects in Java. By encapsulating attributes in set of methods, we ensure that these attributes are accessible and modifiable only through these methods. This helps in maintaining data integrity, program stability, and flexibility of code design. So, it is always a good practice to use getter and setter methods when working with objects in Java.
Popular questions
-
What are getter and setter methods in Java?
Answer: Getter and setter methods are modules in Java that are used to get and set the values of instance variables or attributes of objects in a class. Getter methods get the value of a private field or data variable, and setter methods set the value of an instance variable. -
Why should getter and setter methods be used in Java?
Answer: Getter and setter methods play a crucial role in Java programs as they offer data protection and control of data access, improving the overall design and maintainability of the program. They help maintain data integrity, program stability, and offer encapsulation, making it difficult for unintended interference. -
What are the naming conventions for getter and setter methods?
Answer: The naming convention for getter methods follows the syntax “getVariableName()”, while the naming convention for setter methods follows the syntax “setVariableName(DataType variableName)”. The scope of both should be public. -
Can we modify the attributes of an object without using getter and setter methods?
Answer: No, once the attributes are defined as private, they cannot be accessed or modified from outside the class. Getter and Setter methods offer a controlled way to access and set the value of object attributes. -
Can we change the internal implementation of a class without affecting the program’s external interface?
Answer: Yes, getter and setter methods help you change the internal implementation of your classes without affecting the program’s external interface, as they allow controlled accessing and modifying of object attributes. This way, you can improve the flexibility and maintainability of your program.
Tag
Encapsulation