今天我们花1min了解一下链式编程。
我们先定义一个StudentChain类和他的study方法:
class StudentChain{
public void study(){
System.out.println("Chain:Good Good Study.");
}
}
然后我们定义 一个 StudentChainDemo类和他的 getStudent方法,方法返回的是StudentChain:
class StudentChainDemo{
public StudentChain getStudent(){
return new StudentChain();
}
}
现在我们可以在main方法中测试了:
1.通过StudentChainDemo类的构造方法拿到StudentChainDemo的对象;
2.通过StudentChainDemo对象调用getStudent方法拿到StudentChain的对象;
3.通过StudentChain对象调用study方法成功输出:Chain:Good Good Study.
StudentChainDemo studentChainDemo = new StudentChainDemo();
StudentChain studentChain = studentChainDemo.getStudent();
studentChain.study();
观察代码我可以发现:
studentChain对应于studentChainDemo.getStudent();
那么studentChainDemo.getStudent().study();也是ok的咯。
测试,成功输出:Chain:Good Good Study.
studentChainDemo.getStudent().study()
这就是我们的链式编程,对象调方法在调方法···
前提:对象调完方法后返回的是对象,不然怎么继续调方法···
其实三行代码可以简化为new StudentChainDemo().getStudent().study();
视开发需求而定。