Way to make Java parent class method return object of child class

Viewed 43658

Is there any elegant way to make Java method located within parent class return object of child class, when this method is called from child class object?

I want to implement this without using additional interfaces and extra methods, and to use this without class casts, auxiliary arguments and so on.

Update:

Sorry that I was not so clear.

I want to implement method chaining, but I have problems with methods of parent class: I lose access to child class methods, when i call parent class methods... I suppose that I'v presented the core of my idea.

So the methods should return this object of this.getClass() class.

7 Answers

If you are using Kotlin, you can create an extension function

abstract class SuperClass
class SubClass: SuperClass()

fun <T : SuperClass> T.doSomething(): T {
    // do something
    return this
}

val subClass = SubClass().doSomething()
Related