相关疑难解决方法(0)

为什么要使用getter和setter/accessors?

使用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)

而前者需要很少的样板代码.

java oop getter setter abstraction

1472
推荐指数
26
解决办法
37万
查看次数

Getter-Setter和私有变量

如果我可以通过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)

java private getter-setter

11
推荐指数
1
解决办法
1万
查看次数

增加私有变量的简单方法?

我想知道是否有一种更简单的方法来增加另一个类的私有变量.以下是我通常会如何做到的:

如果我只需要在我的代码中很少这样做:

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)

就够了,我不禁觉得自己过于复杂了.

java

7
推荐指数
1
解决办法
879
查看次数

getAttribute()方法的重点是什么?

我正在做一个任务,要求我们为一个矩形定义一个类,并为它配备各种方法,其中两个是getHeight()getWidth(),除了return this.height;和之外不应该做什么return this.width;.我不明白这一点.如果我想访问width或者height,为什么我不会通过引用this.width而不是this.getWidth()

oop

2
推荐指数
2
解决办法
189
查看次数

使用Java中的getter函数返回可变成员变量(Date/Timestamp)?

我有一个java类:

class MyObj{
  private Timestamp myDate;

  public  Timestamp getMyDate(){ 
       return mydate;
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

当我通过Findbugs检查时,它说:

错误类型和模式:EI - EI_EXPOSE_REP可以通过返回对可变对象的引用来公开内部表示

那么,用Java 编写getterfor DateTimestamp类型的更好方法是什么?

java getter findbugs

2
推荐指数
2
解决办法
1744
查看次数

标签 统计

java ×4

getter ×2

oop ×2

abstraction ×1

findbugs ×1

getter-setter ×1

private ×1

setter ×1