Skip to content
Advertisement

Using set and get methods in java

In my programming class, the teacher said we have to implement a class and use get methods but did not mention set methods in the description. Are they always used or should be used together?

This is what I’ve written so far:

public class Product
{
    private String name;
    private double price;

    // Argument constructor
    public Product(String productName, double productPrice)
    {
        name = productName;
        price = productPrice;
    }


    /**
     * Getting methods
     */


    // The getName method returns the string
    // stored in the "name" field
    public String getName()
    {
        return name;
    }

    // The getPrice method returns the double
    // stored in the "price" field
    public double getPrice()
    {
        return price;
    }
}

Advertisement

Answer

No, setters are not needed at all when implementing immutable classes/objects:

  1. Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.

Immutability means that the state of the object remains constant after object is fully created / constructed.

Similarly, getters are not always required, depending on the specific implementation of the object API.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement