zoukankan      html  css  js  c++  java
  • 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 指针。

  • 相关阅读:
    关于日期
    修改video标签自带按钮的默认样式
    vue相关
    手机
    国内优秀npm镜像
    一些技能整理
    小程序
    $('.mydiv>ul')和$('.mydiv ul')的不同
    Python 字符编码
    Python 正则表达式 补充
  • 原文地址:https://www.cnblogs.com/ljysy/p/7738387.html
Copyright © 2011-2022 走看看