Object类里的toString()

    xiaoxiao2024-12-15  10

    toString()
    object类是所有Java类的根基类如果类的声明中未使用extends关键字指明其基类,则默认基类为Object类Object类中toString()方法默认返回类名+"@"+其哈希编码 public class T_ToString { public String toString() { return "我重写了这个方法"; } public static void main(String[] args) { T_ToString rr = new T_ToString(); System.out.println(rr.toString()); } }
    equals
    object类中定义有public boolean equals(Object obj)提供定义对象是否”相等“的逻辑Oject的equals方法定义为:x.equals(y)当x和y是同一个对象的引用时返回trueString, Date等类重写了Object的equals方法可以根据需要重写equals方法 public class T_Equals { int color; int heigth, weigth; T_Equals(int color, int height, int weight) { this.color = color; this.heigth = height; this.weigth = weight; } public boolean equals(Object obj) { if(obj == null) return false; else { if(obj instanceof T_Equals) { T_Equals t = (T_Equals)obj; if( this.color == t.color && this.heigth ==t.heigth && this.weigth == t.weigth) { return true; } } } return false; } public static void main(String[] args) { T_Equals ii = new T_Equals (1, 2, 3); T_Equals qq = new T_Equals (1, 2, 3); System.out.println(ii == qq);//比较的是两个对象的地址值 System.out.println(ii.equals(qq)); String s1 =new String("猫"); String s2 =new String("猫"); System.out.println(s1.equals(s2)); } }
    最新回复(0)