Initialization of the class
public class Initializeblockclass {
{
field=200;
}
public int field=100;
public initializeblockclass (int value)
{
This.field=value;
}
Public Initializeblockclass ()
{
}
public static void Main (string[] args) {
Initializeblockclass obj=new Initializeblockclass ();
System.out.println (Obj.field);
Obj=new Initializeblockclass (300);
System. Out. println (Obj.field);
}
TODO auto-generated Method Stub
}
Output results;
Initialization is the first use of the class initialization block, the second time with the public int initialization, so the second time covering the first time, the output of the three, in the main The function assigns the initial value to the class initializeblockclass ,so theoutput is covered , so the class initialization has a class initialization block, you can also directly in the class to assign values, you can also use a function to assign a value to the properties of the class, you can also construct the function.
When there is an inheritance relationship between multiple classes, creating a subclass object causes the parent class to initialize the block's execution
For example
Package Fatherandson;
public class Fatherandson {
public static void Main (string[] args) {
Son a=new son ();
A.show ();
}
}
Class father{
String name;
{
Name= "Father";
}
}
Class Son extends father{
int age=30;
void Show ()
{
System.out.println ("name" +name);
System.out.println ("Age" +age);
}
}
Final output Namefather
Age 30
Only static data is allowed in static methods, or instance members of a class can be accessed in a static method
public class Statictest {
public static void Main (String args [])
{
Test b=new test (); B.print ();
}
}
Class Test {
int i=1;
static void print ()
{
Test a=new test ();
System.out.println (A.I);
}
}
Final Output 1
Using the class's static fields and constructors, we can track the number of objects created by a class. Write a class that can be queried at any time to "how many objects have you created"
Package Jishu;
public class jishu{
public static void Main (string[] args) {
Information A = new information ();
A.outputinformation ();
Information B = new information ();
B.outputinformation ();
} }
Class information{
static int num=0;
Information ()
{num++;
}
public void Outputinformation ()
{
System.out.println ("You've created a +num+" Object!) ");
}
}
Java Action Brain 2