第二十三课:重写Object 的toString() equals()方法


import java.util.List;
import java.util.ArrayList;

 class People{

}

class Worker extends People{

    final String nickName;
    private String name;
    private int age;

    public Worker(){

        nickName = "xiaoEr";
    }

    public void setAge(int newAge){
        age=newAge;
    }
    public int getAge(){
        return age;
    }
    public String getName(){
        return name;
    }
    public void setName(String newName){
        name = newName;
   }    

   public String toString(){

    return nickName+ " " +name +" "+ age;
   }

   public boolean equals(Worker w){

        if (!w.name.equals(name)) {
            return false;
        }
        if (!w.nickName.equals(nickName)) {
            return false;
        }
        if (w.age != age) {
            return false;
        }
        return true;

   }
}

public class Boss{

    public static void main(String[] args) {

        List li = new ArrayList();

        Worker encap= new Worker();
        encap.setName("a");
        encap.setAge(21);

        Worker zhangS= new Worker();
        zhangS.setName("a");
        zhangS.setAge(21);

        li.add(encap);
        li.add(zhangS);
        System.out.print(li.toString());
        System.out.print(encap);

        if (zhangS.equals(encap)) {

            System.out.print("相等");
        }else{

            System.out.print("不等");
        }
    }
}

 

你可能感兴趣的:(第二十三课:重写Object 的toString() equals()方法)