Oop 在java类中获取和设置

Oop 在java类中获取和设置,oop,setter,getter,accessor,Oop,Setter,Getter,Accessor,我被难住了。我想通过包含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;

我被难住了。我想通过包含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;
}
以及:


目前,我一直在获取错误,在我的get和set方法中找不到符号。有什么帮助吗?

这些是功能

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

 t.setThing="First Object"; t.updateCounter++;
其他缺点:你会数到两次

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

将代码更改为:

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

  • 要调用函数,需要添加“()”并在其中添加必需的参数
  • setThing方法更新计数器本身,无需在主代码中手动执行
  • updateCounter属性是私有的,不能由其他类直接访问

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

    谢谢,但是如何将该项设置为具有“First Object”的值?当我尝试t.setThing=“first object”时,仍然无法找到符号;
    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");
    }