在Java中覆盖Object类的方法

huangapple go评论83阅读模式
英文:

Overriding method from Object class in Java

问题

为了覆盖在某个子类A中的Object类中的equals方法,覆盖函数的参数类型必须是Object而不是A。像这样:

public boolean equals(Object o) {
...
}

而不是这样:

public boolean equals(A o) {
...
}
英文:

When I want to override method equals from class Object in some subclass A, why type of parameter of overridden function in subclass A has to be Object and not A. Like this

public boolean equals(Object o) {
...
}

and not this:

public boolean equals(A o) {
...
}

答案1

得分: 3

equals是在父类Object中声明的。当您尝试更改参数的类型时,您必然会使其更加限制(因为Object是可能的最不具体的类型)。

假设您尝试执行以下操作:

Object obj = new A();
obj.equals("str"); // 应该返回false

在第二行中,编译器对A一无所知。该变量中可能包含任何内容。就编译器而言,这只是另一个Object。它不关心该方法已在A中被覆盖。Object.equals以Object作为参数,因此这是完全有效的。

如果您的A实现已被更具限制性的类型覆盖,您将会有根本的不兼容性。该方法无法处理String,但完全可以传递一个String。

英文:

equals is declared in the parent class, Object. When you try to change the type of the parameter, you are necessarily making it more restrictive (since Object is the least specific type there can be).

Suppose you try to do this

Object obj = new A();
obj.equals("str"); // should return false

On the second line, the compiler doesn't know anything about A. There could be anything in that variable. As far as the compiler knows, this is just another Object. It doesn't care that the method has been overriden in A. Object.equals takes Object as a parameter, so this is perfectly valid.

If your A implementation had been overriden with a more restrictive type, you would have a fundamental incompatibility. The method cannot handle a String, yet it is perfectly possible to pass one.

答案2

得分: 1

这是因为您正在覆盖而不是重载。当您覆盖任何方法时,方法签名应该相同。

请查看来自https://docs.oracle.com/javase/tutorial/java/IandI/override.html的以下内容:

覆盖方法具有与其覆盖的方法相同的名称、参数数量和类型,以及返回类型。覆盖方法还可以返回被覆盖方法返回类型的子类型。这个子类型被称为协变返回类型。

您还可能会发现此教程有用。

英文:

It is because you are overriding and not overloading. When you override any method, the method signature should be same.

Check the following from lines from https://docs.oracle.com/javase/tutorial/java/IandI/override.html

> The overriding method has the same name, number and type of
> parameters, and return type as the method that it overrides. An
> overriding method can also return a subtype of the type returned by
> the overridden method. This subtype is called a covariant return type.

You may also find this tutorial useful.

答案3

得分: 0

为了在子类中重写一个方法,该方法需要具有相同的名称、相同的参数或签名,以及相同的返回类型(或子类型)。

英文:

In order to override a method in a subclass, the method needs to have the same name, same parameters or signature, and same return type (or sub-type).

huangapple
  • 本文由 发表于 2020年7月30日 23:52:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/63176867.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定