转载

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

我试图用帮助器方法编写一些自定义异常来设置这样的变量:

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

原文  https://codeday.me/bug/20190112/528694.html
正文到此结束
Loading...