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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With