0

我很难过。我想通过包含 getter 和 setter 来优化一些代码。这是我到目前为止所拥有的:

public class ThingHolder {
private int updateCounter=0;
private Object theThing;

public Object getThing() {
    return theThing;
}

public void setThing(Object theThing) {
    this.theThing = theThing;
    updateCounter++;
}

public int getUpdateCounter() {
    return updateCounter;
}

和:

public class ThingHolderTester {
public static void main(String[] args) {
    ThingHolder t = new ThingHolder();

    t.setThing="First Object"; t.updateCounter++;
    System.out.println("The thing is currently " + t.getThing + " and the ThingHolder has been updated " + t.updateCounter + " times");

    t.setThing="Second Object"; t.updateCounter++;
    System.out.println("The thing is currently " + t.getThing + " and the ThingHolder has been updated " + t.updateCounter + "times");
}

目前我不断收到错误,在我的 get 和 set 方法上找不到符号。请问有什么帮助吗?

4

4 回答 4

1

Change your code to:

public class ThingHolderTester {
public static void main(String[] args) {
    ThingHolder t = new ThingHolder();

    t.setThing("First Object");
    System.out.println("The thing is currently " + t.getThing() + " and the ThingHolder has been updated " + t.getUpdateCounter() + " times");

    t.setThing("Second Object");
    System.out.println("The thing is currently " + t.getThing() + " and the ThingHolder has been updated " + t.getUpdateCounter() + "times");
}

Problems:

  1. To call a function you need to add "()" and add required arguments within.
  2. The setThing method updates the counter itself, no need to do it in main code manually.
  3. The updateCounter property is private and cannot be accessed directly by other class.
于 2013-06-02T19:06:16.720 回答
1

那些是函数

要使用函数,您需要使用括号调用它。

于 2013-06-02T18:35:33.443 回答
0
 t.setThing="First Object"; t.updateCounter++;

其他故障:你会数两次!

第一次调用 .setThing,第二次调用 t.updateCounter。

于 2013-06-02T18:37:33.550 回答
0

创建类时,您可以使用可以在 netbeans 或 eclipse 中插入的 get 和 set(插入代码 -> getter 和 setter)。然后在 main 中调用这些函数,创建所创建类的新实例。

于 2015-08-03T20:50:51.903 回答