使用getter和setter的优点是什么 - 只能获取和设置 - 而不是简单地使用公共字段来存储这些变量?
如果getter和setter做的不仅仅是简单的get/set,我可以非常快地解决这个问题,但我并不是100%清楚如何:
public String foo;
Run Code Online (Sandbox Code Playgroud)
更糟糕的是:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Run Code Online (Sandbox Code Playgroud)
而前者需要很少的样板代码.
如果我可以通过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;
}
Run Code Online (Sandbox Code Playgroud) 我想知道是否有一种更简单的方法来增加另一个类的私有变量.以下是我通常会如何做到的:
如果我只需要在我的代码中很少这样做:
pc.setActionsCurrent(pc.getActionsCurrent()-1);
Run Code Online (Sandbox Code Playgroud)
如果我需要做很多增量,我会做一个特殊的setter:
//In the PC class
public void spendAction(){
this.actionsCurrent--;
}
//In the incrementing Class
pc.spendAction();
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来解决这个问题?如果变量是公开的
pc.actionsCurrent--;
Run Code Online (Sandbox Code Playgroud)
就够了,我不禁觉得自己过于复杂了.
我正在做一个任务,要求我们为一个矩形定义一个类,并为它配备各种方法,其中两个是getHeight()和getWidth(),除了return this.height;和之外不应该做什么return this.width;.我不明白这一点.如果我想访问width或者height,为什么我不会通过引用this.width而不是this.getWidth()?
我有一个java类:
class MyObj{
private Timestamp myDate;
public Timestamp getMyDate(){
return mydate;
}
...
}
Run Code Online (Sandbox Code Playgroud)
当我通过Findbugs检查时,它说:
错误类型和模式:EI - EI_EXPOSE_REP可以通过返回对可变对象的引用来公开内部表示
那么,用Java 编写getterfor Date和Timestamp类型的更好方法是什么?