Using static fields and constructors for classes, you 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?" ”
Public class Track { staticprivateint count=0; Track () { count++ ; } Public Static void inquries () { System.out.println ("Now created object" +count+ "a");} }
Track
Why is the following code not compiled? Where did it go wrong?
Public class Test { publicstaticvoid main (string[] args) { Foo obj1 New Foo (); }} class foo{ int value; Public int InitValue) { = initvalue; }}
Test
If the class provides a custom construction method, the system will no longer provide a default construction method
What is the output of the following code, using the classes defined in the previous page slide?
Public class Initializeblockclass { { = $; } Public int field=100; Public int value) { this. field=value; } Public Initializeblockclass () { }}
Initializeblockclass
Public Static void Main (string[] args) { new initializeblockclass (); System.out.println (Obj.field); // ? New Initializeblockclass (+); System.out.println (Obj.field); // ?}
Main
Please summarize the rules of Java field initialization according to the output result of the code.
Executes the default value specified by the class member definition or the initialization block of the class, exactly which one you want to see in front of.
Run the Teststaticinitializeblock.java sample, observe the output, and summarize the "Order of execution of static initialization blocks".
classroot{Static{System.out.println ("Static initialization block of root"); } {System.out.println ("Root's normal initialization block"); } PublicRoot () {System.out.println ("Root parameterless constructor"); }}classMidextendsroot{Static{System.out.println ("Static initialization block for mid"); } {System.out.println ("Normal initialization block for mid"); } PublicMid () {System.out.println ("No parametric constructor for mid"); } PublicMid (String msg) {//calling overloaded constructors in the same class through this This(); System.out.println ("Mid with parametric constructor, its parameter value:" +msg); }}classLeafextendsmid{Static{System.out.println ("Static initialization block of the leaf"); } {System.out.println ("Plain initialization block of the leaf"); } PublicLeaf () {//A constructor that invokes a string argument in the parent class through Super Super("Java Initialization sequence Demo"); System.out.println ("The constructor that executes the leaf"); }} Public classteststaticinitializeblock{ Public Static voidMain (string[] args) {NewLeaf (); }}
Teststaticinitializeblock.java
Executes the static initialization block of the parent class before executing the initialization block of the class
Class and object hands-on brain