带继承关系的链式调用

本文介绍了一种实现链式调用的方法,并解决了在继承关系中调用基类方法时类型转换的问题。通过泛型类的设计,使得子类方法与基类方法能够在链式调用中自由切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在一个单类中,我们写链式调用可以这样:

public class B {
    public B funB1() {
        return this;
    }

    public B funB2() {
        return this;
    }
}

使用方法:

B b = new B();
b.funB1().funB2().funB1();




现在如果带有继承关系:

public abstract class A {
    public A funA() {
        return this;
    }
}

public class B extends A {
    public B funB1() {
        return this;
    }

    public B funB2() {
        return this;
    }
}

使用时会发现,一旦调用了A类的方法,就无法再调用B类的方法了,因为此时返回的对象是A了,无法切换回B。

B b = new B();
b.funB1().funB2().funA().funA().funA()...



解决方法

public abstract class A<T extends A<?>> {

    public T getThis() {
        return (T) this;
    }

    public T funA() {
        return getThis();
    }
}

public class B extends A<B> {
    public B funB1() {
        return this;
    }

    public B funB2() {
        return this;
    }
}

使用方法:

B b = new B();
b.funB1().funB2().funA().funA().funA().funB1().funB2();
Java 中实现方法的链式调用(Method Chaining),主要依赖于每个方法返回当前对象的引用,从而允许连续调用其他方法。这种方式可以让代码更加简洁、易读,并且适合流式编程风格。 ### 实现方式 要实现链式调用,需要在类的方法中返回 `this`,即当前对象实例的引用。这样可以在一个语句中连续调用多个方法,而不需要每次都重新获取对象。 例如,定义一个 `Person` 类并实现链式调用[^4]: ```java public class Person { private String name; private int age; private String job; // 设置姓名的方法 public Person setName(String name) { this.name = name; return this; // 返回当前对象的引用 } // 设置年龄的方法 public Person setAge(int age) { this.age = age; return this; // 返回当前对象的引用 } // 设置职业的方法 public Person setJob(String job) { this.job = job; return this; // 返回当前对象的引用 } // 打印信息的方法 public void printInfo() { System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Job: " + job); } } ``` 通过上述实现,可以使用如下方式进行链式调用: ```java Person person = new Person(); person.setName("Alice").setAge(30).setJob("Engineer").printInfo(); ``` 该示例展示了如何通过返回 `this` 来实现方法的链式调用,使得代码更紧凑和直观。 ### 注意事项 1. **避免过度使用**:虽然链式调用可以提高代码可读性,但过多的方法串联可能会导致调试困难。 2. **保持逻辑清晰**:确保链式调用中的每个方法都具有明确的功能,以避免代码复杂化。 3. **兼容性考虑**:如果类被设计为继承结构的一部分,则需要注意链式调用对子类的影响。 ### 示例说明 另一个常见的链式调用实现是定义一个 `Point` 类来设置坐标值[^2]: ```java public class Point { private int x; private int y; public Point x(int x) { this.x = x; return this; } public Point y(int y) { this.y = y; return this; } @Override public String toString() { return "x = " + this.x + ", y = " + this.y; } } ``` 调用方式如下: ```java Point point = new Point(); point.x(10).y(20); System.out.println(point); // 输出: x = 10, y = 20 ``` 这种实现方式同样基于返回 `this` 的机制,允许连续调用多个方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值