How to make Superclass Method returns instance of SubClass

和自甴很熟 提交于 2019-12-21 17:46:50

问题


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.


回答1:


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




回答2:


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;
}


来源:https://stackoverflow.com/questions/28820288/how-to-make-superclass-method-returns-instance-of-subclass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!