gpt4 book ai didi

继承

转载 作者:搜寻专家 更新时间:2023-10-31 19:30:56 26 4
gpt4 key购买 nike

给定这些类:

class Father {
public Father getMe() {
return this;
}
}

class Child extends Father { .. }

我正在从子类调用父类的公共(public)方法:

Child c = new Child();
Child c1 = c.getMe();

所以,这是行不通的,我必须使用强制转换才能使其工作:

Child c1 = (Child) c.getMe();

问题是:有没有更好的方法让它在没有强制转换的情况下工作?可以这样?? :

public <T extends Father> T getMe() {
return this;
}

提前致谢。

最佳答案

您应该在 Child 类中覆盖返回类型为 Child 的 getMe 方法。此功能称为协变返回,它带有 jdk1.5 ..

class Child extends Father{  
public Child getMe() {
return this;
}
}

这个解决方案怎么样?它看起来并不优雅,你应该在 getThis 方法中转换为 T。但是没有必要在子类中重写 getThis 方法。但不幸的是,类型安全没有被强制执行,可以定义这样一个基础对象,Base<Child> baseChild = new Base<Child>();所以我不推荐这种方法..

class Base<T extends Base<T>> {
public T getThis() {

return (T) this;
}
}

class Child extends Base<Child>{

}

Child child = new Child();
child.getThis(); // return type is Child
Base base = new Base();
base.getThis(); // return type is base

关于继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5420522/

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