重写toString()

 重写Object的toString()之前,得到的结果是  类型 @ 内存地址

demo:

package cn.sasa.demo1;

public class Test {
	public static void main(String[] args) {
		Person p1 = new Person("sa", 12);
		//Person p2 = new Person("sasa", 121);
		//p2 = p1;
		//boolean b = p1.equals(p2);
		//System.out.println(b);
		System.out.println(p1.toString());
	}
}

  

package cn.sasa.demo1;

public class Person {
	private String name;
	private int age;
	
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return this.age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	/**
	 * 重写equals , 比较age是否相同
	 */
	public boolean equals(Object obj) {
		//return this == obj; //比较内存地址
		if(obj == null) {
			return false;
		}
		if(this == obj) {
			return true;
		}
		if(obj instanceof Person) {
			Person p = (Person)obj;
			return this.getAge() == p.getAge();
		}
		return false;
	}
	
	/**
	 * 重写toString()
	 */
	public String toString() {
		return "name:" + this.getName() + " age:" + this.getAge();
	}
}

  

 

posted @ 2018-12-12 10:14  SasaL  Views(208)  Comments(0Edit  收藏  举报