Java fifth week after class homework

Source: Internet
Author: User

Title: Using static fields and constructors of classes, we can track the number of objects created by a class. Write a class that can query it at any time "how many objects have you created?" ”。

Programming Ideas:

A static variable is explicitly referenced first, so there can be only one public class in the topic, so in the program, the reference static variable sets the number of times the object is created, so that when the number of objects created is +1, the +1 of the static variable is convenient to count, and in the public class, the number of times that the output creates the object.

Source:

Package demo; class Jishu {    privatestaticint  A;      Public Jishu ()    {        a++    ;    }  Public Static int Get ()    {        return  A;    }}
Package demo; Public classNum { Public Static voidMain (string[] args) {//TODO Auto-generated method stubsJishu j1=NewJishu (); Jishu J2=NewJishu (); Jishu J3=NewJishu (); Jishu J4=NewJishu (); System. out. println ("the number of objects you have created is:"+jishu.Get()); }}

Program run:

Java fifth week after class homework

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.