Concept
How can the toString() method represent a Java object?
ComputerScienceOne / Common Methods
"The toString() method returns a String representation of the object. However, the default behavior that all classes inherit from the Object class is that it returns a string containing the fully qualified class name (package and class name) along with a hexadecimal representation of the JVM memory address at which the instance is stored. An example with our Student class may produce something like: unl.cse.Student@272d7a10.\n\nWe can override this functionality and change the behavior of the toString() method to return whatever we want. To do so, we simply define the function (with a signature that matches the toString() method in the Object class) in our class.\n\npublic String toString() {\n\nreturn String.format(\"%s, %s (ID = %d); %.2f\",\n\nthis.lastName,\n\nthis.firstName,\n\nthis.id,\n\nthis.gpa);\n\n}\n\nThis example would return a String containing something similar to \"Hamilton, Margaret (ID = 4321); 3.90\". The toString() method is a very convenient way to print instances of your class."
Related Ideas
- How do you use Java instances and invoke their methods?ComputerScienceOne · Usage
- What common methods do Java classes inherit?ComputerScienceOne · Usage
- What does the completed Java Student class example contain?ComputerScienceOne · Example
- How do you declare and instantiate Java class instances?ComputerScienceOne · Usage
- What is composition in object-oriented class design?ComputerScienceOne · Common Methods