Object类的说明:一切类都是Object类的子类
提供ToString()方法,返回该对象的描述性字符串如: 类名@hashCode值,很多时候,程序员需要重写toString()方法。
class Apple { private String color; private double weight; public Apple(){} public Apple(String color, double weight) { this.color = color; this.weight = weight; } public String toString() { return "一个苹果颜色是:" + color + ", 一个苹果重量是:" + weight; } } public class ToStringTest { public static void main(String[] args) { Apple a = new Apple("红色", 5.68); System.out.println(a); } }
输出:一个苹果颜色是:红色, 一个苹果重量是:5.68
说明:public String toString重写ToString方法,主要是给更好的展示结果。