Sitemap
Javarevisited

A humble place to learn Java and Programming better.

Photo from Unsplash by Blake Connally

Member-only story

The Difference between A Setter Method and Constructor When Setting a Variable’s Value

3 min readApr 1, 2024

--

Java provides different ways to set a value of an instance variable of a class. Among them are two common approaches: using the constructor and using the setter method. In this article we’re going to address the difference between both.

Setting a Value Using the Setter Method

Setter methods are widely used in Java applications along with the getter methods to work with instance variables of classes. They provide a way to safely modify the values of private variables after creating an instance of a class:

public class Item {
private String category;

public void setCategory(String newCategory) {
this.category = newCategory;
}

public String getCategory() {
return category;
}
}

Here we created a class called Item with one member variable category and a setter method setCategory which accepts an argument newCategory.This method is used to update the value of original category. Let’s call this method to further illustrate this:

public static void main(String[] args) {
Item item = new Item();
item.setCategory("electronics");
}

As you can see, we called the setter method and passed a String. Now if we call the getter to retrieve the…

Javarevisited
Javarevisited

Published in Javarevisited

A humble place to learn Java and Programming better.

Firas Ahmed
Firas Ahmed

Written by Firas Ahmed

Hey, I'm a backend developer and I love to share what I learn with the community.

No responses yet