是否可以覆盖 Java 中的类参数?我很确定这是不可能的,但是......
public class Dad {
protected Building home;
public Dad() {
}
public Building getHome(){
return this.home;
}
}
public class Son extends Dad {
protected Shack home;
public Son () {
super();
this.home = new Shack();
}
}
public Shack extends Building{
(...)
}
显然,添加两个同名的参数没有问题,但我不确定这两个参数是否“链接”在一起。
当我从 Son
对象调用 getHome()
函数时,它返回一个 null 对象。这是有道理的,因为 Dad
对象没有初始化的 Building
对象。即使 Son
有一个扩展 Building
类的初始化 Shack
对象。 (不知道我说得够不够清楚……)
一个简单的解决方案是简单地使用 Shack
对象初始化 home
,并在任何时候在 Shack
中强制转换 home
有必要。但我想知道是否还有其他方法可以做到这一点。
最佳答案
字段不能被覆盖。在您的案例字段中,儿子只是 hiding爸爸的田野:
Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. [...] Generally speaking, we don't recommend hiding fields as it makes code difficult to read.
将 GetHome
函数声明到 Dad
类中,因此它只能看到 home
实例形式 Dad
,即无效的。您可以从 Son 实例以 super.home
的形式访问爸爸的 home
。
您可以提取父类(super class)或接口(interface)。
interface HasHome {
Building getHome();
}
class Dad implements HasHome {
protected Building home;
public Dad() {
this.home = new Building();
}
@Override
public Building getHome(){
return this.home;
}
}
class Son implements HasHome { // Or extends Dad
protected Shack home;
public Son () {
super();
this.home = new Shack();
}
@Override
public Shack getHome() {
return home;
}
}
有another question选择哪种方式。此外,父类(super class)型可以是泛型的,正如 @Lorelorere 所示。
关于java - 重写Java中的类参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55374455/