Getter和Setter的概念是控制类中变量的访问。这样,如果需要在内部更改值以以不同的方式表示它,就可以这样做而不会破坏类外部的任何代码。
例如,假设您有一个距离变量的类,它是以英寸为单位测量的。几个月过去了,您在很多地方使用此类,并突然意识到需要用厘米表示该值。如果您没有使用Getter和Setter,那么您将不得不追踪每个类的用途并进行转换。如果您使用Getter和Setter,只需更改这些方法,使用该类的所有内容都不会受到影响。
public class Measurement
{
/**
* The distance in centimeters.
*/
private double distance;
/**
* Gets the distance in inches.
* @return A distance value.
*/
public double getDistance()
{
return distance / 2.54;
}
/**
* Sets the distance.
* @param distance The distance, in inches.
*/
public void setDistance(double distance)
{
this.distance = distance * 2.54;
}
}