Getter-Setter 和私有变量
2022-09-04 02:40:01
如果我可以通过 getter 返回的引用来更改私有变量的值,那么它不是绕过 setter 方法吗?难道它违背了 getter-setter 和私有变量的目的吗?
public class Test{
private Dimension cannotBeChanged;
public Test(int height, int width)
{
if(height!=3)
cannotBeChanged.height = height;
if(width!=3)
cannotBeChanged.width = width;
}
public Dimension getDimension()
{
return cannotBeChanged;
}
public void setDimension(int height, int width)
{
if(height!=3)
cannotBeChanged.height = height;
if(width!=3)
cannotBeChanged.width = width;
}
public static void main(String [] args)
{
Test testOne = new Test(5,5);
Dimension testSecond = testOne.getDimension();
testSecond.height = 3; //Changed height and width to unwanted values
testSecond.width= 3;
}