Trying to reference a variable from another object (JAVA)

Skiddswarmik :

I'm just starting to learn Java and trying to make a 'Counter' class to compliment another class 'CounterTesting' as an object.This is how I set up my Counter Class:

public class Counter
{
  public int count;

  public Counter()
  {
    count = 0
  }

  void click()
  {
    count += 1;
  }
}

And this is my main class:

public class CounterTesting
{
    public static void main(String[] args)
    {
        Counter c1 = new Counter();
        Counter c2 = new Counter();

        System.out.println("Counter 1: " + c1 + "    Counter 2: " + c2);

        c1.click();
        c1.click();
        c1.click();
        c1.click();
        c1.click();

        c2.click();
        c2.click();
        c2.click();

        System.out.println("Counter 1: " + c1 + "    Counter 2: " + c2);
    }
}

but when I run it, c1 and c2 print "Counter@686a1b3f" evert time it's printed. I think whats happening is it's calling the class itself and not the variable but I'm not sure how to fix it. Thanks in advance!

Jason :

Yeah so it's printing out the name of the class and the hashCode() relative to that class. This is because every Object in java has a toString function that does what I just described. If you override the toString function to provide relative information like the counter integer, you can print it. An alterative would be to directly reference the counter variable in the Counter class.

@Override
public String toString() {
    return String.format("counter=%s, counter);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=349033&siteId=1