MinusKube
MinusKube

Reputation: 67

How to make Superclass Method returns instance of SubClass

I have a class called Test and a class called SubTest who extends Text, I would like to have a method in the Test class who will returns the instance of SubTest when called, I would like to do :

SubTest test = new SubTest().setTest("Hello!").setOtherTest("Hi!");

The setTest() and setOtherTest() methods should be in the Test class.

But when I do :

public Test setTest(String test) { return this; }

It only returns the instance of Test so I have to cast Test to SubTest, but I don't want to.

Is it possible ? If yes, how ?

Thanks, MinusKube.

Upvotes: 6

Views: 2798

Answers (2)

isnot2bad
isnot2bad

Reputation: 24444

Having a method return its owner (this) to be able to 'chain' multiple method calls is called fluent API. You can solve your problem by using generics, although the resulting code might be somehow less readable though:

public class Person<T extends Person<T>> {
    public T setName(String name) {
        // do anything
        return (T)this;
    }
}

public class Student extends Person<Student> {
    public Student setStudentId(String id) {
        // do anything
        return this;
    }
}

public class Teacher extends Person<Teacher> {
    public Teacher setParkingLotId(int id) {
        // do anything
        return this;
    }
}

Now, you do not need any casts:

Student s = new Student().setName("Jessy").setStudentId("1234");
Teacher t = new Teacher().setName("Walter").setParkingLotId(17);

See also: Using Generics To Build Fluent API's In Java

Upvotes: 10

rgettman
rgettman

Reputation: 178263

It is possible to have those methods return a SubTest, because Java's return types are covariant.

You must override those methods so that you can return this, a SubTest, in SubTest, e.g.:

@Override
public SubTest setTest(String message) {
    super.setTest(message);  // same functionality
    return this;
}

Upvotes: 0

Related Questions