September 13, 2012

How to refer to "this" in abstract Java class?

Question by user1111929

Is it possible in Java to use this inside a method of an abstract class, but as an instance of the subclass at hand, not just of the abstract class?

abstract class MyAbstractClass <MyImplementingClass extends MyAbstractClass> {

    public abstract MyImplementingClass self();
}

which I overwrite in every subclass I with

class MyImplementingClass extends MyAbstractClass<MyImplementingClass> {

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

but I wonder if there are more elegant methods to do this. In particular, one that doesn’t require every subclass to overwrite a routine like self().

Answer by amit

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

Answer by Starx

I believe, you can return newInstance() of a class to behave like that

@Override public MyImplementingClass self() {
    return MyImplementingClass.newInstance();
}
...

Please fill the form - I will response as fast as I can!