cascading calls to Java functions

Source: Internet
Author: User

Tag: The Count function returns a sample call to a cascading object concat ABC

The method of the string class can be called consecutively: string str= "abc"; String Result=str.trim (). toUpperCase (). Concat ("DEFG");

Please read the source code of the above methods of the string class in the JDK, imitate its programming method, write a MyCounter class, its method also supports the above "cascade" invocation feature,

Examples of its invocation are:

MyCounter counter1=new MyCounter (1);

MyCounter counter2=counter1.increase, decrease (2). Increase (3);

....

Source code of the program:

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, decrease (45); System.out.println (counter2.a);}}

The result of the program is:

Note: In this program, if you want to implement a cascade call like the string type, the type of each function should be this class in the program, returning the object of that class with the this pointer.

cascading calls to Java functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.