public class People
{
private String name;
private int age;
public People(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
//对People中的具体内容进行比较,比较他的名字和年龄。
public boolean equals(People p)
{
if (p.getName().equals(this.getName()))
{
if (p.getAge() == this.getAge())
return true;
}
else
{
return false;
}
return false;
}
}
public class PeopleDemo
{
public static void main(String[] args)
{
People a = new People("zhangsan", 7); //新建一个对象
People b = new People("zhangsan", 7); //又新建了一个对象
System.out.println(a == b);//这里比较的两个类对象在内存中的地址值,结果是false
System.out.println(a.equals(b));//这里复写了People类中的equals方法返回true,如没有复写equals方法的话返回false.
}
}
|