A Construction method
1. Source Code
public class test{
public static void Main (string[] args) {
Foo obj1=new foo ();
}
}
Class foo{
int value;
Public Foo (int initvalue) {
Value=initvalue;
}
}
2. Procedures
3. Results analysis
If the construction method is provided, the system no longer provides a default construction method.
Two JAVA Field Initialization
1. Source Code
public class Initializeblockdemo {
public static void Main (string[] args) {
Initializeblockclass obj=new Initializeblockclass ();
System.out.println (Obj.field);
Obj=new Initializeblockclass (300);
System.out.println (Obj.field);
}
}
Class initializeblockclass{
{
field=200;
}
public int field=100;
public initializeblockclass (int value) {
This.field=value;
}
Public Initializeblockclass () {
}
}
2. Procedures
3. Results analysis
For Java Field initialization problems, no inheritance: initialization block first execution, field initializer code second execution, constructor third execution.
Three. Initialization issues with inherited conditions
1. Source Code
Class b{
Public B () {
System.out.println (" Fourth execution of the parent constructor ");
}
{
System.out.println (" The third execution of the parent dynamic code block ");
}
static {
System.out.println ("The first execution of the parent class static block ");
}
}
public class A extends b{
Public A () {
System.out.println (" sub-class constructor Sixth execution ");
}
{
System.out.println (" subclass dynamic code block fifth execution ");
}
static {
System.out.println (" sub-class static block second execution ");
}
public static void Main (string[] args) {
New A ();
}
}
2. Procedures
Four
Object Initialization order: first executes the parent class static content, after the parent class static content execution completes, executes the subclass content. After the subclass executes, go to see if the parent class has no non-static block of code, if any, execute. Parent class non-static code block ---> Parent class construction method ---> subclass Non-static code block ---> Subclass construction method.
Five After-school homework write a class, at any time can query the number of objects created
1. Source Code
public class test { private int id; private string name; private static long count; private final static threadlocal tl=new threadlocal (); public test () { super (); count++; tl.set (count); } public long getcount () { return (Long) tl.get (); } public static void main (String[] args) { for (int i = 0; i < 5; i++) { test t=new test (); system.out.println (T.getCount ()); } } }
2. Procedures
Java Job 3