String类的方法可以连续调用: String str="abc"; String result=str.trim().toUpperCase().concat("defg");
请阅读JDK中String类上述方法的源码,模仿其编程方式,编写一个MyCounter类,它的方法也支持上述的“级联”调用特性,
其调用示例为:
MyCounter counter1=new MyCounter(1);
MyCounter counter2=counter1.increase(100).decrease(2).increase(3);
….
程序的源码:
public class Mycounter { private int a; public Mycounter() { } public Mycounter(int a) { this.a=a; } public Mycounter increase(int x) { this.a=this.a+x; return this; } public Mycounter decrease(int x) { this.a=this.a-x; return this; } public static void main(String[] args) { Mycounter counter1=new Mycounter(1); Mycounter counter2=counter1.increase(100).decrease(45); System.out.println(counter2.a); } }
程序的结果截图为:
注:在该程序中,如果想实现类似string类型那样的联级调用,每个函数的类型应该是该程序中的本类,返回该类的对象用this 指针。