【问题标题】:get and set in java classes在 java 类中获取和设置
【发布时间】:2013-06-02 18:34:43
【问题描述】:

我很难过。我想通过包含 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 方法上找不到符号。请问有什么帮助吗?

【问题讨论】:

    标签: oop setter getter accessor


    【解决方案1】:

    将您的代码更改为:

    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");
    }
    

    问题:

    1. 要调用函数,您需要添加“()”并在其中添加所需的参数。
    2. setThing 方法自行更新计数器,无需在主代码中手动进行。
    3. updateCounter 属性是私有的,不能被其他类直接访问。

    【讨论】:

      【解决方案2】:

      这些是函数

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

      【讨论】:

      • 谢谢,我如何将 theThing 设置为具有“第一个对象”的值?当我尝试 t.setThing = "first object"; 时,我仍然找不到符号
      【解决方案3】:
       t.setThing="First Object"; t.updateCounter++;
      

      其他错误:你会数两次!

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多