[Valid Java] 2. when too many constructor parameters exist, define tivejava

Source: Internet
Author: User

[Valid Java] 2. when too many constructor parameters exist, define tivejava

Package cn. xf. cp. ch02.item2;/***** function: when there are many construction parameters out of the controllable range, use build Mode Time: 8:25:05 PM file: NutritionFacts. java ** @ author Administrator **/public class NutritionFacts {private final int param1; private final int param2; private final int param3; private final int param4; private final int param5; private final int param6; private final int param7; public static void main (String [] args) {// initialize NutritionFacts test = new NutritionFacts. builder (1, 2 ). param3 (3 ). param4 (4 ). param5 (5 ). param6 (6 ). param7 (7 ). build ();} private NutritionFacts (Builder build) {param1 = build. param1; param2 = build. param2; param3 = build. param3; param4 = build. param4; param5 = build. param5; param6 = build. param6; param7 = build. param7;} public static class Builder {private final int param1; private final int param2; private int param3 = 0; private int param4 = 0; private int param5 = 0; private int param6 = 0; private int param7 = 0; public Builder (int param1, int param2) {this. param1 = param1; this. param2 = param2;} public Builder param3 (int val) {param3 = val; return this;} public Builder param4 (int val) {param3 = val; return this ;} public Builder param5 (int val) {param3 = val; return this;} public Builder param6 (int val) {param3 = val; return this;} public Builder param7 (int val) {param3 = val; return this;} 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.