简体   繁体   English

Java类的多态性

[英]Polymorphism with Java class

suppose we have a class Employee with the following data field and function. 假设我们有一个Employee类,它具有以下数据字段和功能。 The program attempts to see if 2 Employees are equal by comparing their name and address 该程序尝试通过比较其nameaddress来查看2名Employees是否相等

public class Employee{
  private String name;
  private double hours;
  private double rate;
  private Address address;
    @Override
    public boolean equals(Object obj){
        if(obj == this) return true;
        if(obj == null) return false;
        if(this.getClass() == obj.getClass()){
            Employee other = (Employee) obj;
            return name.equals(other.name) && address.equals(other.address);
        }else{
            return false;
        }
    }

why didn't we do this instead public boolean equals(Employee obj) (different parameters)? 为什么我们不这样做,而是改为使用public boolean equals(Employee obj) (不同的参数)?

(1) if you do new Empolyee().equals(null) - this will happen. (1)如果执行new Empolyee().equals(null) -将会发生。

(2) Because the Object class declared equals(Object) - and you cannot put Employee as a parameter in order to override this method. (2)因为Object类声明了equals(Object) -并且您不能将Employee作为参数来覆盖此方法。 You can only widen the parameter when overriding a method, never narrow it. 您只能在覆盖方法时加宽参数,而从不缩小参数。
What will happen if you then do: 如果您这样做,将会发生什么:

Object o = new Employee();
o.equals(new Object());

The "method" will have no idea how to handle this case, while it is perfectly valid and cannot be known (in the general case) in compile time. “方法”不知道如何处理这种情况,尽管它是完全有效的,并且在编译时无法得知(通常情况下)。

To avoid it, this type of variance is not allowed when overriding a method, and you will get a compilation error if you try to do it. 为了避免这种情况,在重写方法时不允许使用这种类型的方差,如果尝试执行此操作,则会出现编译错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM