toString() method in Java
The
toString()
method returns a textual representation of an object. A basic implementation is already included in java.lang.Object
and so because all objects inherit from java.lang.Object
it is guaranteed that every object in Java has this method.
Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the
toString()
method. So use a meaningful implementation but use it for technical purposes.
===============================ToStringClass ======================================
public class ToStringClass {
public String toString() {
return "Hello I am ToStringClass\n";
}
public ToStringClass() {
System.out.println(this);
}
}
=====================================MainClass====================================
public class MainClass {
public static void main(String[] args) {
ToStringClass toStringObject = new ToStringClass();
}
}
=======================================OUTPUT===================================
Hello I am ToStringClass
In most languages,
toString
or the equivalent method just guarantees that an object can be represented textually.
This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string.
Objects often implement custom
toString
behavior so that the method actually tells you something about the object instance. For example, a Person
class might override it to return "Last name, First name" while a Date
class will show the date formatted according to some default setting (such as the current user interface culture).
good one , nice info !!
ReplyDeleteThanks brother
ReplyDeleteThank you. Found it interesting and useful. Java is a general purpose, high-level, class-based and object-oriented programming language. And we provide Java training at Fita.
ReplyDeleteThoughtful blog you have here
ReplyDelete