那我用String类型时,会说我没有重写方法
时间: 2024-04-22 09:27:16 浏览: 25
如果你在实现 `Comparator` 接口时使用了 `String` 类型作为比较对象,那么编译器会报错并提示你需要重写 `compare` 方法。这是因为 `Comparator` 接口的 `compare` 方法定义为 `public int compare(T o1, T o2)`,其中的 `T` 表示一个泛型类型,需要在实现时指定具体的类型。如果你指定了 `String` 类型,那么实现时就需要按照指定的类型进行重写。如果你没有重写该方法或者重写方法时参数类型不正确,编译器就会报错。
相关问题
String如何重写了equals方法
在Java中,重写equals方法通常是为了比较两个对象的内容是否相等。以下是String类如何重写equals方法的示例代码:
```
public class MyString {
private String str;
public MyString(String str) {
this.str = str;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof MyString)) {
return false;
}
MyString other = (MyString) obj;
if (str == null) {
return other.str == null;
} else {
return str.equals(other.str);
}
}
}
```
这里我们创建了一个自定义的MyString类,并重写了它的equals方法。在equals方法中,我们首先判断两个对象是否是同一个对象,如果是则返回true。然后判断obj是否是MyString类型的对象,如果不是则返回false。最后,我们使用String类的equals方法比较两个字符串是否相等,如果相等则返回true,否则返回false。注意,我们还要处理str为null的情况,如果str为null,则只有other.str也为null时才返回true。
重写方法能够重写方法的返回值类型吗
是的,重写方法可以重写方法的返回值类型,但是返回值类型必须是原始方法返回值类型的子类型。这意味着,如果原始方法返回值类型为Object,则重写方法的返回值类型可以是任何类的子类。如果原始方法返回值类型为String,则重写方法的返回值类型可以是String或String的子类。但是,如果重写方法的返回值类型是原始方法返回值类型的父类,则编译器会报错。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)