• Post Reply Bookmark Topic Watch Topic
  • New Topic

toString() method invoked  RSS feed

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code below works fine i am not clear about one point is that
how the toString() method (line 35) is invoked when it is not called can anyone explain...

1. package test;
2.
3. class Book1
4. {
5. private String title;
6. private String author;
7.
8. Book1()
9. {
10. this("unknown", "unknown");
11. }
12
13. Book1(String title, String author)
14. {
15. this.title = title;
16. this.author = author;
17. }
18.
19. public String getTitle() {
20. return ( title );
21. }
22.
23. public void setTitle(String str){
24. title = str;
25. }
26.
27. public String getAuthor() {
28. return(author);
29. }
30.
31. public void setAuthor(String str) {
32. author = str;
33. }
34.
35. public String toString() // how this method is invoked
36. {
37. return(" Title : " + title + "\nAuthor: " + author);
38. }
39. }
40.
41. class TestBook
42. {
43. public static void main(String[] args)
44. {
45. Book1 b1 = new Book1();
46. System.out.println(b1);
47.
48.
49. b1.setTitle("Java1");
50. b1.setAuthor("A");
51.
52.
53. System.out.println("Title: " + b1.getTitle() );
54. System.out.println("Author: " + b1.getAuthor() );
55. }
56. }
 
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method toString() is invoked when you pass an instance of the object to println() in line 46.
 
Glenny Dsilva
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So it gets automatically called when u print the instance.
 
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To be more precise,

PrintStream.print(Object o)

calls

String.valueOf(o)

which calls o.toString() if o != null.

System.out is a PrintStream.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!