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();
}
}