sách gpt4 ăn đã đi

继承

In lại 作者:搜寻专家 更新时间:2023-10-31 19:30:56 27 4
mua khóa gpt4 giày 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 getMe() {
return this;
}

Cảm ơn trước.

câu trả lời hay nhất

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

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

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

class Base> {
public T getThis() {

return (T) this;
}
}

class Child extends Base{

}

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/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress