在Java里面,每一个类都会隐式地继承object类,而在object类里面有toString方法,这个就是用来输出类地地址。 System.out.println(this) 它会自动调用this对象的toString方法,所以若不重写toString方法地话,就会调用object类地toString方法,也就是输出当前对象的地址。 示例:
package test1;
public class Student { private int price; private String category; public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Student(int price, String category) { this.price = price; this.category = category; } //重写toString方法 public String toString(){ return "price:"+price+"category:"+category; } }
输出Student package test1;
public class StudentTest {
public static void main(String[] args) { Student st=new Student(1,"category"); System.out.print(st); } }
结果 price:1category:category 若不重写toString方法则输出 test1.Student@142bece
|