You must use the constructor to construct multiple constructor parameters.

Source: Internet
Author: User

You must use the constructor to construct multiple constructor parameters.

General overlapping constructor mode:

 

Public class NutritionFacts {private final int one; private final int two; private final int three; public NutritionFacts (int one, int two, int three) {this. one = one; this. two = two;} public NutritionFacts (int one) {this (one, 0);} public NutritionFacts (int one, int two) {this (one, two, 0) ;}} // when calling the page, the value of NutritionFacts nt = new NutritionFacts (, 0); // disadvantage: overlapping constructor mode. When there are many parameters, difficult to write and read;

Improvement: Builder mode:

Public class NutritionFacts {private final int one; private final int two; private final int three; private NutritionFacts (Bulider builder) {one = builder. one; two = builder. two; three = builder. three;} public static class Builder {private String name; private int one = 0; private int two = 0; private int three = 0; public Builder (String name) {this. name = name;} public Builder one (int value) {one = value; reture this;} public Builder two (int value) {two = value; reture this ;} public Builder two (int value) {two = value; reture this;} // call, and finally instantiate the external class public NutritionFacts build () {return new NutritionFacts (this );}}}

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.