Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Superclass Method returns instance of SubClass

Tags:

java

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.

like image 325
MinusKube Avatar asked Mar 02 '15 22:03

MinusKube


1 Answers

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

like image 79
isnot2bad Avatar answered Oct 28 '22 17:10

isnot2bad