Java – how do I call the default implementation of “toString”?

If toString is not defined, Java uses some hashes to print the class name If toString is defined, how to implement this function?

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());

    }
}

Solution

The default toString implementation just connects the object's class name "@" with its hexadecimal hashcode

public static String defaultToString(Object o) {
    return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>