Java函数的联级调用

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 指针。

 

转载于:https://www.cnblogs.com/ljysy/p/7738387.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值