Java抽象类:为派生类返回“this”指针

栏目: C · 发布时间: 6年前

内容简介:翻译自: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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

500 Lines or Less

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》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具