Home > Blockchain >  Using set and get methods in java
Using set and get methods in java

Time:10-18

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;
    }
}

CodePudding user response:

You don't necessarily have to have both of them.

In its current form, the Product class would be immutable - once you've created it, you can't change its properties (since there is no method that would let you do so). In fact, this pattern could be beneficial in some usecases.

CodePudding user response:

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.

  • Related