java 重写toString()与equal()的方法

为了程序的优雅,我们需要重写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));
	}

}


完美
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值