如视频教程,若我用父类animal创建一个对象dog,,用子类dog创建一个dog2,并对两个对象的name和age赋相同的值,用equal方法对比时为什么显示不相同?
如视频教程,若我用父类animal创建一个对象dog,,用子类dog创建一个dog2,并对两个对象的name和age赋相同的值,用源码改过equal方法,对比时为什么显示不相同?核心代码如下:
package com.imooc; public class Pig { public int age=20; public String name="pig"; @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pig other = (Pig) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } public class Pig2{ public int age=20; public String name="pig"; } public class Initial { public static void main(String[] args) { Pig pig=new Pig(); Pig2 pig2=new Pig2(); if(pig.equals(pig2)){ System.out.println("相同"); }else { System.out.println("不相同"); } } }