Alex Rivera | Logout

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

Asked 2010-10-27T09:49:30.833
38

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.

Edit
Report

1 Answer

0
public class Parent {
    public Parent myMethod(){
        return this;
    }
}
public class Child extends Parent {}

And invoke it like

       Parent c = (new Child()).myMethod();
       System.out.println(c.getClass());

Is this solution is correct? If it is, then, how is it different from the #1 solution?

answered 2010-10-27T10:28:04.557

Your Answer