1

在Java中是否可以在this抽象类的方法中使用,但作为手头子类的实例,而不仅仅是抽象类的实例?

abstract class MyAbstractClass <MyImplementingClass extends MyAbstractClass> {

    public abstract MyImplementingClass self();
}

我在每个子类中覆盖它

class MyImplementingClass extends MyAbstractClass<MyImplementingClass> {

    @Override public MyImplementingClass self() {
        return this;
    }
}

但我想知道是否有更优雅的方法可以做到这一点。特别是,它不需要每个子类都覆盖像self().

4

3 回答 3

3

The issue here I believe is that your self() method returns MyImplementingClass and not MyAbstractClass.

You should return a MyAbstractClass, the dynamic type of the returned object will be the relevant one.

I also do not follow why wouldn't you just use this? It returns the object itself, with the correct dynamic type, regardless of where it is called. You can cast it if you need to

于 2012-09-13T06:21:17.633 回答
1

在 Java 中重写方法时,您可以将返回类型重写为原始类型的子类。此代码完全有效:

abstract class MyAbstractClass {

    public MyAbstractClass self() {
        return this;
    }
}

具体类:

class MyImplementingClass extends MyAbstractClass {

    @Override
    public MyImplementingClass self() {
        return this;
    }
}

这也是为什么您可以覆盖clone()以返回确切类型而不仅仅是Object

public class SomeCloneable implements Cloneable {

    @Override
    public SomeCloneable clone() {
        return new SomeCloneable();
    }
}
于 2012-09-13T06:01:29.697 回答
0

我相信,你可以返回newInstance()一个班级来表现得像那样

@Override public MyImplementingClass self() {
    return MyImplementingClass.newInstance();
}
于 2012-09-13T05:58:38.013 回答