内容简介:翻译自:https://stackoverflow.com/questions/18204190/java-abstract-classes-returning-this-pointer-for-derived-classes
我试图用帮助器方法编写一些自定义异常来设置这样的变量:
public class KeyException extends RuntimeException {
protected String Id;
protected KeyException(String message) {
super(message);
}
protected KeyException(String message, Throwable cause) {
super(message, cause);
}
public String getId() {
return keyId;
}
public KeyException withId(final String Id) {
this.Id = Id;
return this;
}
}
但是,在我的派生类中,我不能使用“withId”方法,因为它只返回基类 – 无论如何返回“this”指针而不必覆盖每个派生类中的方法?
is there anyway to return the “this” pointer without having to override the method in every single derived class?
是的,请看下面的选项1.
您可以通过以下几种方式执行此操作:
>将结果转换为派生类
>在子类中重写它
>将返回类型更改为void.由于您在对象上调用方法,因此您已经有了指向它的指针.
翻译自:https://stackoverflow.com/questions/18204190/java-abstract-classes-returning-this-pointer-for-derived-classes
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- C++ 基类指针和派生类指针之间的转换
- c – 通过指向其基类的指针删除派生对象
- 如何强制调用C#派生方法
- MidnightBSD 1.0 发布,FreeBSD 派生的操作系统
- MidnightBSD 1.0 发布,FreeBSD 派生的操作系统
- Quirky 8.6 发布,从 Puppy 派生的 Linux 发行版
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
500 Lines or Less
Amy Brown、Michael DiBernardo / 2016-6-28 / USD 35.00
This book provides you with the chance to study how 26 experienced programmers think when they are building something new. The programs you will read about in this book were all written from scratch t......一起来看看 《500 Lines or Less》 这本书的介绍吧!