如何使超类方法返回子类的实例 [英] How to make Superclass Method returns instance of SubClass

查看:36
本文介绍了如何使超类方法返回子类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Test 的类和一个名为 SubTest 的类,它扩展了 Text,我想在 中有一个方法>Test 类将在调用时返回 SubTest 的实例,我想做:

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

setTest()setOtherTest() 方法应该在 Test 类中.

但是当我这样做时:

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

它只返回Test 的实例,所以我必须将Test 转换为SubTest,但我不想这样做.

可能吗?如果是,如何?

谢谢,MinusKube.

解决方案

让方法返回其所有者 (this) 以能够链接"多个方法调用被称为 fluent API.您可以通过使用泛型来解决您的问题,尽管结果代码的可读性可能会降低:

public class Person>{public T setName(String name) {//做任何事情返回 (T)this;}}公共类 Student 扩展 Person{公共学生 setStudentId(String id) {//做任何事情返回这个;}}公共类教师扩展了 Person{公共教师 setParkingLotId(int id) {//做任何事情返回这个;}}

现在,您不需要任何演员表:

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

另见:使用泛型在 Java 中构建 Fluent API

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

这篇关于如何使超类方法返回子类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆