7月21日总结

Object类的 equals方法
public boolean equals(Object obj)方法 定义对象是否“相等”的逻辑。
需要查阅API文档,文档中详细解释:
自反性:对于任何非空引用值 x,x.equals(x) 都应返回 true。
对称性:对于任何非空引用值 x 和 y,当且仅当 y.equals(x) 返回 true 时,x.equals(y) 才应返回 true。
传递性:对于任何非空引用值 x、y 和 z,如果 x.equals(y) 返回 true,并且 y.equals(z) 返回 true,那么 x.equals(z) 应返回 true。
一致性:对于任何非空引用值 x 和 y,多次调用 x.equals(y) 始终返回 true 或始终返回 false,前提是对象上 equals 比较中所用的信息没有被修改。
对于任何非空引用值 x,x.equals(null) 都应返回 false。
练习程序TestEquals.java:
public class TestEquals {
 public static void main(String[] args) {
  Cat c1 = new Cat(1, 2, 3);
  Cat c2 = new Cat(1, 2, 3);
  System.out.println(c1 == c2);
  System.out.println(c1.equals(c2));
 }
}

class Cat {
 int color;
 int height,weight;
 
 public Cat(int color, int height, int weight) {
  this.color = color;
  this.height = height;
  this.weight = weight;
 }
 
 public boolean equals(Object obj) {
  if(obj == null) return false;
  else {
   if(obj instanceof Cat) {
    Cat c = (Cat)obj;
    if(c.color == this.color && c.height == this.height && c.weight == this. weight) {
    
     return true;
    }
   }
  }
  return false;
 }
 
 
}

为了对比Cat  c1和c2需要重写equals方法,用来比较color,height,weight
public boolean equals(Object obj) {
  if(obj == null) return false;
  else {
   if(obj instanceof Cat) {
    Cat c = (Cat)obj;
    if(c.color == this.color && c.height == this.height && c.weight == this. weight) {
    
     return true;
    }
   }
  }

多态:动态绑定,不需要改动原来 的核心程序,这就是面向对象的可扩展性。
应用多态的条件1.要有继承
       2.要有重写
       3.父类引用指向子类对象
程序如下:
 class Animal {
  private String name;
  Animal(String name)  {  this.name = name; }
 
  public void enjoy() {
    System.out.println("叫声......");
  }
 
 
}

  class Cat extends Animal {
  private String eyesColor;
  Cat(String n,String c) {super(n); eyesColor = c;}
 
  public void enjoy() {
    System.out.println("猫叫声......");
  }
 
}

  class Dog extends Animal {
  private String furColor;
  Dog(String n,String c) {super(n); furColor = c;}
 
  public void enjoy() {
    System.out.println("狗叫声......");
  }
}

class Bird extends Animal {
  Bird() {
    super("bird");
  }
  public void enjoy() {
    System.out.println("鸟叫声......");
  }
}

class Lady {
    private String name;
    private Animal pet;
    Lady (String name,Animal pet) {
        this.name = name;  this.pet = pet;
    }
    public void myPetEnjoy(){pet.enjoy();}
}

public class Test {
    public static void main(String args[]){
        Cat c = new Cat("catname","blue");
        Dog d = new Dog("dogname","black");
        Bird b = new Bird();
        Lady l1 = new Lady("l1",c);
        Lady l2 = new Lady("l2",d);
        Lady l3 = new Lady("l3",b);
        l1.myPetEnjoy();
        l2.myPetEnjoy();
        l3.myPetEnjoy();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值