Java: use static fields and constructors to query the number of created objects. java Constructor

Source: Internet
Author: User

Java: use static fields and constructors to query the number of created objects. java Constructor

Problem: using static fields and constructors of a class, we can track the number of objects created by a class.

Please write a class and you can query it at any time, "How many objects have you created ?".

Program Design ideas:

Use static variables to specify a counter number,

When creating an object, you always need to execute the constructor once,

Then, when the constructor executes the seasonal number auto-increment,

The number of objects created at the end is displayed.

Program flowchart:

 

Source code:

1/** 2*3 */4 5/** 6 * @ author letter 1605-3 20163471 Wu Xin 7*8 */9 public class NumofObj {10 11/** 12*13 */14 15 private static int number = 0; 16 public NumofObj () {17 // TODO automatically generated constructor stubs 18 number ++; 19} 20 21/** 22 * @ param args23 */24 25 public static int getNumber () 26 {27 return number; 28} 29 public static void main (String [] args) {30 // TODO automatically generated method stub 31 NumofObj t1 = new NumofObj (); 32 NumofObj t2 = new NumofObj (); 33 NumofObj t3 = new NumofObj (); 34 NumofObj t4 = new NumofObj (); 35 NumofObj t5 = new NumofObj (); 36 NumofObj t6 = new NumofObj (); 37 NumofObj t7 = new NumofObj (); 38 System. out. println ("created in total" + NumofObj. getNumber () + "objects"); 39} 40 41}

The running result is as follows:

Related Article

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.