Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top