I am a newbie in java. Say, I have a class Individual. I want to print
Individual ind = new Individual();
System.out.println(ind);
Above code gives output like this:
Individual@1922221
- What is the significance of this?
- Is it some kind of unique id
for that object? - Can I customize this? I mean write a function of
my own which will give output when I print? - If so, how can I do
this?
If you want to print meaningful content of any object, you have to implement your own
toString()method, which will override the parent(Object) class’stoString()method. By default all the classes(Whatever you create) extendsObjectclass.Sample Code:
Output:
If you have bigger class with many variables, you can use XStream to implement your toString() method. XStream will print your object meaningful in XML format. Even you can parse them back to equivalent object. Hope this would help you.