面向对象同通识13(_toString和equals)
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@776ec8dftoString.Apple@776ec8df*/
默认的toString:Object提供的toString方法返回: 类名@hashCode方法返回值
重写toString:在上述Apple类增加重写方法
public String toString(){return color+"\n"+weight;}
此时AppleTest类将返回:
/*null0.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方法,重写后当两个字符串字符内容相等就会返回trueSystem.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));}}/*falsetrue*/
在实际运用中,用来作为equals比较的成员变量——挑选关键的比较即可。
