If toString
is not defined, then Java prints class name with some hash. How to reach this functionality if toString
is defined?
package tests.java.lang;
public class Try_ToString {
public static class MyClass {
protected int value;
public MyClass(int value) {
this.value = value;
}
}
public static class MyClass2 extends MyClass {
public MyClass2(int value) {
super(value);
}
@Override
public String toString() {
return String.valueOf(value);
}
}
public static void main(String[] args) {
MyClass a = new MyClass(12);
MyClass b = new MyClass2(12);
System.out.println("a = " + a.toString());
System.out.println("b = " + b.toString());
}
}
By default the toString() method will return a string that lists the name of the class followed by an @ sign and then a hexadecimal representation of the memory location the instantiated object has been assigned to.
The toString() method returns the String representation of the object. If you print any object, Java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depending on your implementation.
JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.
The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called. Here are some of the advantages of using this method.
The answer from @immibis is correct, however it wouldn't work if your class override the hashcode method. But you can use System.identityHashcode
.
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.
public static String defaultToString(Object o) {
return o.getClass().getName() + "@" +
Integer.toHexString(System.identityHashCode(o));
}
The default toString
implementation just concatenates the object's class name, "@", and its hashCode
in hexadecimal.
public static String defaultToString(Object o) {
return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With