class Person
{
private String name;
private int age;
public Person(String name,int age)
{
this.name=name;
this.age=age;
}
//get、set方法略
public String getinfo()
{
return this.name+">"+this.age;
}
public boolean equals(Object obj) //对equals()方法覆写,覆写的代码几乎一样,要掌握。equals方法的参数是Object,这点要注意
{
if(thisobj)
{
return true;
}
if(!(obj instanceof Person))
{
return false;
}
Person per=(Person)obj; //向下转型,按说必须先有向上转型才能向下转型,但Object类己默认实现了向上转型,必须明白这点.
//if(this.name.equals(per.name) && (this.ageper.age))
if((this.nameper.name) && (this.age==per.age))
{
return true;
}
else
{
return false;
}
}
}
//****************************************************************************************************
public class PersonDemo
{
public static void main(String[] args)
{
Person per1=new Person(“张三”,14);
Person per2=new Person(“张一”,14);
System.out.println(per1.equals(per2));
}
}
Java equals()方法覆写学习
最新推荐文章于 2023-05-31 18:40:02 发布