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
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
toString
method on A class to return the representation you wantFor example:
class A{
private int x;
public A() {
x = 0;
}
public String toString() {
return "A:"+x;
}
}