为了程序的优雅,我们需要重写toString与equal
class Apple//定义一个苹果类
{
private String color;
private double weight=0;
public Apple()//生成构造器
{
}
public Apple(String a,double b)
{
this.color=a;
this.weight=b;
}
}
我们可以在类中定义成员函数来完成类中信息以及它父亲信息的,但是我们希望我们通过System.out.println(类名)
来完成我们需要重写toString
public String toString()
{
return "颜色:"+color+" 重量:"+weight;
}
好了,现在我们就完成了toString的重写
下面是事例代码
package java第三次作业;
class Apple//定义一个苹果类
{
private String color;
private double weight=0;
public Apple()//生成构造器
{
}
public Apple(String a,double b)
{
this.color=a;
this.weight=b;
}
public String toString()
{
return "颜色:"+color+" 重量:"+weight;
}
}
public class Testtoday
{
public static void main(String[] args)
{
new Apple();
Apple T=new Apple("红色",5.0);
System.out.println(T);
}
}
我们在比较俩个类的时候会出现这样的情况
Apple a =new Apple(“红色”,2.0);
Apple a1 =new Apple(“红色”,2.0);
我们在比较的时候用a==a1或a.equals(a1)的时候输出的都是false.解决这种问题是方法是重写equals.默认的equals方法的比较依据是与==相同的
public boolean equals(Object obj)
{
if(this==obj)//a.equals(a)的形式输出true
{
return true;
}
if(obj!=null&&obj.getClass()==Apple.class)//不等于空而且类型相同
{
Apple o=(Apple)obj;
return this.color==o.color&&this.weight==o.weight;
//需要比较的俩个都相同
}
return false;
}
下面是全部测试代码。
package java第三次作业;
class Apple//定义一个苹果类
{
private String color;
private double weight=0;
public Apple()//生成构造器
{
}
public Apple(String a,double b)
{
this.color=a;
this.weight=b;
}
public String toString()
{
return "颜色:"+color+" 重量:"+weight;
}
public boolean equals(Object obj)
{
if(this==obj)
{
return true;
}
if(obj!=null&&obj.getClass()==Apple.class)//类型相同
{
Apple o=(Apple)obj;
return this.color==o.color&&this.weight==o.weight;
}
return false;
}
}
public class Testtoday
{
public static void main(String[] args)
{
new Apple();
Apple T=new Apple("红色",5.0);
System.out.println(T);
String n=T+"";
System.out.println(n);
Apple T1=new Apple("红色",5.0);
System.out.println(T.equals(T1));
}
}
完美