Ancestor class method equals the sample Java rewrite

  Java is a very important point is the knowledge that all classes inherit Object class default, so every class you create inherits Object methods, all classes can be upcast to Object class object, of course, a common method which can override Object sometimes rewrite is necessary, such as equals and toString method of the object class method of rewriting; original equals method to compare two objects is whether the references are equal, the original toString method returns a reference to an object.

public class TestEquals {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object object){
        Obj TestEquals = (TestEquals) Object;    // high-low type to type 
        IF (obj.getName () == the this .getName ()) {   // the same objects as the same name of the object 
            return  to true ; 
        } 
        return  to false ; 
    } 

    @override 
    public String toString () { 
        the StringBuilder SB = new new the StringBuilder (); 
        sb.append ( "name:" + the this .getName () + "\ n-" + "Age" + the this .getAge ());
         return SB. toString ();    // the StringBuilder override toString method returns a string se 
    }

     public  static void main(String[] args) {
        TestEquals obj1 = new TestEquals();
        TestEquals obj2 = new TestEquals();
        obj1.setName("张三");
        obj1.setAge(18);
        obj2.setName("张三");
        System.out.println(obj1.equals(obj2));
        System.out.println(obj1.toString());
    }
}

 

Guess you like

Origin www.cnblogs.com/chiweiming/p/11353562.html