在 java 中使用 set 和 get 方法

Using set and get methods in java

在我的编程class中,老师说我们要实现一个class并使用get方法,但在描述中没有提到set方法。它们总是被使用还是应该一起使用?

这是我到目前为止写的:

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

您不必同时拥有它们。

在当前形式下,Product class 将是不可变的 - 一旦创建它,​​就无法更改其属性(因为没有方法可以让您这样做所以)。事实上,这种模式在某些用例中可能是有益的。

不,实现时根本不需要 setter immutable classes/objects:

  1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.

不变性意味着对象的状态在对象完全创建/构造后保持不变。

同样,吸气剂并不总是需要的,这取决于对象的具体实现API。