面向对象同通识13(_toString和equals)

面向对象同通识13(_toStringequals

toString方法

public class Apple {
    private String color;
    private double weight;
    public Apple(){

    }

    public void setColor(String color){
        this.color=color;
    }
    public String getColor(){
        return this.color;
    }
    public void setWeight(double weight){
        this.weight=weight;
    }
    public double getWeight(){
        return this.weight;
    }
}
public class AppleTest {
    public static void main(String[] args) {
        Apple gtn = new Apple();
        System.out.println(gtn);
        System.out.println(gtn.toString());//与上一句效果相同
       //程序打印对象,或者将对象自动转化为字符串的时候,实际上用的都是该对象将的`toString`方法的返回值
    }
}
/*
toString.Apple@776ec8df
toString.Apple@776ec8df
*/

默认的toStringObject提供的toString方法返回: 类名@hashCode方法返回值

重写toString:在上述Apple类增加重写方法

public String toString(){
        return color+"\n"+weight;
    }

此时AppleTest类将返回:

/*
null
0.0
*/

equals方法

==运算符如果判断两个引用类型的变量,要求两个引用变量指向同一个对象时,才会返回true

public class AppleTest {
    public static void main(String[] args) {
        Apple g1=new Apple();
        Apple g2=new Apple();
        System.out.println(g1==g2);
    }
}
/*
false
*/

此时需要Object类中的equals方法来判断从而达到需求,

默认的equals方法判断和==运算符功能完全相同

此时需要重写equals方法来提供两个对象相等的标准

Apple类中的重写方法如下:

public boolean equals(Object obj){
        //如果二者指向同一对象
        if(this==obj){
            return true;
        }
        //obj必须是Goat类型并且不为空
        if (obj!=null&&obj.getClass()==Goat.class){
            Goat target=(Goat) obj;
            return this.color.equals(((Goat) obj).color)&&this.weight==target.weight;
            //对于此处判断引用类型的color,见下文例str
        }
        else {
            return false;
        }
    }

Str

public class Str {
    public static void main(String[] args) {
        String a=new String("233");
        String b=new String("233");
        System.out.println(a==b);
        //String类已经重写equals方法,重写后当两个字符串字符内容相等就会返回true
        System.out.println(a.equals(b));
    }
}

此时就可以判断Apple类中的color变量了

public class AppleTest {
    public static void main(String[] args) {
        Apple g1=new Apple();
        Apple g2=new Apple();
        System.out.println(g1==g2);
        System.out.println(g1.equals(g2));
    }
}
/*
false
true
*/

在实际运用中,用来作为equals比较的成员变量——挑选关键的比较即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值