SNOWSD

导航

JAVA编程思想 Ch3.6题

练习6:在练习5的基础上,创建一个新的Dog索引,并对其赋值为Spot对象。测试用==和equals()方法来比较引用结果。

 1 public class quan {
 2     String name;
 3     String says;
 4 
 5     public void setName(String name){
 6         this.name =name;
 7     }
 8 
 9     public String getName() {
10         return name;
11     }
12 
13     public String getSays() {
14         return says;
15     }
16 
17     public void setSays(String says) {
18         this.says = says;
19     }
20 }
public class Dog {

    public static void main(String[] args) {
        quan spot = new quan();
        quan scruffy = new quan();
        quan xiaoQ = new quan();

        spot.setName("spot");
        scruffy.setName("scruffy");
        xiaoQ.setName("spot");

        spot.setSays("Ruff!");
        scruffy.setSays("Wuff!");
        xiaoQ.setSays("Ruff!");

        System.out.println(spot.getName());
        System.out.println(spot.getSays());
        System.out.println(scruffy.getName());
        System.out.println(scruffy.getSays());
        System.out.println(xiaoQ.getName());
        System.out.println(xiaoQ.getSays());

        //引用不相等之前
        System.out.println("spot.equals(xiaoQ):" + spot.equals(xiaoQ));
        System.out.print("spot == xiaoQ:");
        System.out.println(spot == xiaoQ);

        xiaoQ = spot;

        //将spot引用赋值给xiaoQ
        System.out.println("spot.equals(xiaoQ):" + spot.equals(xiaoQ));
        System.out.print("spot == xiaoQ:");
        System.out.println(spot == xiaoQ);
    }
}

 

 

posted on 2020-04-30 17:19  SNOWSD  阅读(133)  评论(0编辑  收藏  举报