Вопрос

i'm stumped. i want to optimise some code by including getters and setters. this is what i have so far:

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

and:

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

at the moment i keep getting error cannot find symbol on my get and set methods. any help please?

Это было полезно?

Решение

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.

Другие советы

Those are functions.

To use a function, you need to call it, using parentheses.

 t.setThing="First Object"; t.updateCounter++;

Other fault: You will count up twice!

First call in .setThing, second in t.updateCounter.

When creating the class you can use the get and set that can be inserted either in netbeans or eclipse (insert code -> getter and setter). And then make the call to those functions in the main creating a new instance of the class created.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top