-3

What is displayed by Line 1 Below? BlueJ prints out A@18fea98, but I don't think this is correct. Please help, thank you.

class A{
  private int x;
  public A(){
    x=0;
  }
}

//test code in client program
A test = new A();
out.println(test);//LINE 1
J. Doe
  • 1
  • 1
  • 1
    What do you expect it to print? – Amit Feb 07 '16 at 19:17
  • It is correct - http://stackoverflow.com/questions/4712139/why-does-the-default-object-tostring-include-the-hashcode – radoh Feb 07 '16 at 19:17
  • 2
    "The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object." – BoDidely Feb 07 '16 at 19:18

1 Answers1

0

By default, out.println(obj) will invoke the toString method on object test, which by default will return the HashBased memory location of the object on which toString is invoked.

In your scenario: A@18fea98

Which is expected output. If you need to print the value of the x attribute, you have following two options

  1. Call the getter to get the value of the attribute
  2. Override the toString method on A class to return the representation you want

For example:

    class A{
       private int x;
       public A() { 
         x = 0;
       }

       public String toString() {
          return "A:"+x;
       }
   }
Akash Yadav
  • 2,411
  • 20
  • 32
  • Thank you, how can I override the toString method? – J. Doe Feb 07 '16 at 19:27
  • I have updated the answer with a sample implementation, the output will be "A:0" in the current case. Feel free to modify the toString implementation as needed. also if the answer satisfied, please do accept the answer so that others might find it helpful – Akash Yadav Feb 07 '16 at 19:28