Reputation: 19395
Right now the default toString()
method displays the internal identifier for the object.
How do I make the toString()
method display object variables instead?
thanks!
Upvotes: 0
Views: 3792
Reputation: 15242
@Override
public String toString()
{
String yourString = "";
//Do things to get what you want
return yourString;
}
Upvotes: 1
Reputation: 10641
Inherit the class and override its toString() method to display whatever you want.
Upvotes: 0
Reputation: 120376
You need to override toString()
on the class you want the information about.
For example:
class Foo {
private String myProperty = "bar";
@Override
public String toString() {
return myProperty;
}
}
In the above example, you would see the following:
new Foo().toString(); // outputs "bar"
Upvotes: 2
Reputation: 120268
you need to override the toString method on your class. In it you return a String that you will construct based on the class properties.
So if you class was
class Person {
String firstName;
String lastName;
}
you would add
public String toString() {
return firstName + " " + lastName;
}
thats just a basic example. In real code I would use String.format() method, or possibly the apache StringBuilder tool, which will automatically generate a String for any object.
Upvotes: 1