Java Applet (Classroom Assignment 03)

Source: Internet
Author: User

using the class's static fields and constructors, 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?" ”。

idea: Because the static initialization block runs only once, is a good way to record the number of times, define a static private int variable, call the constructor variable plus one, and then write a method to return the value of the variable, the implementation of the query to create the function of how many objects.

Flow chart

ImportJava.util.Scanner; Public classtestjing { Public Static voidMain (String[]args) {Jingtai a=NewJingtai ();  while(true) {System.out.println ("Please select function: 1 Create object, 2 query Create object number, 0 exit!" "); Scanner SC=NewScanner (system.in); intI=Sc.nextint (); if(i==1) {a=NewJingtai (); System.out.println ("Created successfully! "); }            Else if(i==2) {A.chaxun (); }               Else{System.out.println (Goodbye "); return; }        }    }}classjingtai{Private Static intNumber ; Static{ number=0; }     PublicJingtai () { number++; }     Public intGetNumber () {returnNumber ; }     Public  voidChaxun () {intb= This. GetNumber (); System.out.println ("Created" +b+ "objects"); }}

A static variable number is defined in a class, initialized only once, creating an object number++, and several objects are created by number.

Java Applet (Classroom Assignment 03)

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.