toString()方法:
java.lang.Object類的toString()方法的定義如下:
public String toString(){
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
1.當打印一個對象的引用時,實際上默認調用的就是這個對象的toString()方法
2.當打印的對象所在的類沒有重寫Object中的toString()方法時, 那么調用的就是Object中定義toString()方法。
返回此對象所在的類及對應的堆空間實體的首地址值。
3.當打印的對象所在的類重寫了toString()方法時,調用的就是我們自己重寫的toString()方法;
注:常這樣重寫:將對象的屬性信息返回,
4.像String類 包裝類,File類 Date類等,已經實現了Object類中toString()方法的重寫。
TestToString:
package com.aff.equals; import java.util.Date; import com.aff.java1.Person; public class TestToString { public static void main(String[] args) { Person p1 = new Person("AA", 10); System.out.println(p1.toString());// com.aff.java1.Person@6d06d69c System.out.println(p1);// com.aff.java1.Person@6d06d69c String str = "AA"; String str1 = new String("BB"); System.out.println(str); System.out.println(str1.toString()); Date d = new Date(); System.out.println(d); } }
輸出結果:
com.aff.java1.Person@6d06d69c
com.aff.java1.Person@6d06d69c
AA
BB
Wed Mar 18 19:14:58 CST 2020
注意:double類型轉為String類型 :String.valueOf(radius)
e2:
Circle:
package com.aff.equals; public class Circle extends GeometricObject { private double radius; public Circle() { super(); this.radius = 1.0; } public Circle(double radius) { super(); this.radius = radius; } public Circle(double radius, String color, double weight) { super(color, weight); this.radius = radius; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } // 圓的面積 public double findArea() { return Math.PI * radius * radius; } // 重寫equals()方法和toString() public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof Circle) { Circle c = (Circle) obj; return this.radius == c.radius; } else { return false; } } @Override public String toString() { return "Circle [radius=" + radius + "]"; } /* public String toString() { return radius + ""; }*/ }
GeometricObject:
package com.aff.equals; public class GeometricObject { protected String color; protected double weight; public GeometricObject() { super(); this.color = "white"; this.weight = 1.0; } public GeometricObject(String color, double weight) { super(); this.color = color; this.weight = weight; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } }
TestCircle:
package com.aff.equals; public class TestCircle { public static void main(String[] args) { Circle c1 = new Circle(2.3); Circle c2 = new Circle(2.3); System.out.println(c1.equals(c2));// false-->true System.out.println(c1.toString()); } }
輸出結果:
true
Circle [radius=2.3]