怎么比较两个不同子类的值是否相等?
package com.imooc; public class Animal { public String name; public int age; @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Animal other = (Animal) obj; if (age != other.age) return false; return true; } }
package com.imooc; public class Dog extends Animal { }
package com.imooc; public class Cat extends Animal { }
package com.imooc; public class Initial { public static void main(String[] args) { Dog dog = new Dog(); Dog dog2=new Dog(); Cat cat = new Cat(); dog.age=1; dog2.age=1; cat.age=1; if(dog.equals(dog2)){ System.out.println("dog和dog2的age相同"); }else{ System.out.println("dog和dog2的age不同"); } if(dog.equals(cat)){ System.out.println("dog和cat的age相同"); }else{ System.out.println("dog和cat的age不同"); } } }
结果为dog和dog2的age相同,dog和cat的age不同
为什么new同一个子类时,equals可以比较属性值,而new不同子类时,不能比较属性值,怎么修改才能比较不同子类的属性值
谢谢