gpt4 book ai didi

java - 了解java编译器

转载 作者:行者123 更新时间:2023-12-01 16:53:50 25 4
gpt4 key购买 nike

假设我有这两个类,位于不同的文件中:

public class Text
{
public String _word;

public Text(String w)
{
_word = w;
}

public String getWord()
{
return _word;
}

public boolean equals (Text other)
{
return ((other!=null)&&(_word.equals(other._word)));

}
public boolean test (Text other)
{
return 1==1;

}
}

二等:

public class Sentence
{
public String _word;

public Sentence(String w)
{
_word = w;
}

public String getWord()
{
return _word;
}

public boolean equals (Object other)
{
return ((other!=null) && (other instanceof Sentence)
&& (_word.equals(((Sentence) other)._word)));
}
}

主要内容如下:

public static void main(String[]args){

Text y1 = new Text("abc");
Sentence z1 = new Sentence ("abc");
**
}

假设我运行以下命令,其中 ** 为:

System.out.println (y1.equals(z1));

一切正常,输出“false”。

但是,如果我运行这个命令:

System.out.println (y1.test(z1));

编译器尖叫“句子无法转换为文本”。

两个问题:

  1. 为什么它适用于 equals 但不适用于 test? y1 是 Text,因此调用 y1.equlas() 会调用 Text 内的 equlas(),并且仅获取 Text 作为参数。
  2. 如果它确实有效,为什么输出是错误的?两个“_word”都设置为“abc”。

谢谢!

最佳答案

您已在 Text 中定义了 equals(Text) 方法。但是,它不会覆盖从 Object 继承的现有 equals(Object) 方法。因此,您的 equals(Text) 方法会重载 Object 中的 equals(Object) 方法。因此,您可以调用y1.equals(z1)。由于 z1 是一个 Sentence,因此调用的是 equals(Object) 方法。 Sentence 对象与 Object 匹配,但与 Text 不匹配。 equals method in Object比较对象引用以查看它们是否相同。

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

它们不是,所以它返回false

您已在 Text 中定义了 test(Text) 方法。没有其他可用的重载,并且 Sentence 根本不匹配 Text,因此编译器会提示。

顺便说一句,您在 Sentence 中定义的 equals(Object) 方法是对 equals 的正确重写,用于检查 null 和参数的类。

关于java - 了解java编译器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35487921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com