Class initialization
Create a class using the new keyword and initialize it by calling the constructor of the class. Constructors can assign values to attributes of a class.
Member variables
Member variables: outside methods, inside classes. Also a class attribute
Note the default values of member variables when they are not assigned.==String is also an object with an initial default value of NULL ==
Static properties, static code blocks, normal properties, normal methods, normal method blocks, constructor initialization order
- Static properties: Properties that are static
- Static method blocks: blocks of code included in static{}
- Normal properties: properties that are not static (call method output tests for effect)
- Normal method blocks: blocks of code included in {}
- Constructor: Method with the same class name, used to initialize the method
- Methods: Normal methods that are effective when called
public class LifeCycle {
// Static properties
private static String staticField = getStaticField();
// Static code block
static {
System.out.println("StaticField:" + staticField);
System.out.println("2: Static code block");
}
// Common properties are initialized by calling the spectrum method
private String field =getField();
// Common method block
{
System.out.println("4: Normal method block initializes field:" + field);
}
private String getField(a) {
System.out.println("3: Normal properties");
return "field";
}
private static String getStaticField(a) {
System.out.println("1: Static properties");
return "staticField";
}
// The constructor
public LifeCycle (a){
System.out.println("5: Constructor initialization");
}
public static void main(String[] args) {
newLifeCycle(); }}Copy the code
Execution result:
1: static attribute staticField: staticField2: Static code block3: Common property4: normal method block initializes field:field5The: constructor is initializedCopy the code
Initialization of an array
int[] a; Or generally use the followingint a[];
Copy the code
Direct assignmentint array[3] = {1.2.3}; The third value of partial assignment isintThe default value of0
int array[3] = {1.2}; The assignment parameter determines the length of the array. The length of the next example is2
int array[] = {1.2};
Copy the code
Variable parameter method
public int add (int. numbers){
int sum = 0;
for(int num : numbers){
sum+=num;
}
returnsum; } call method add();// No parameter is passed
add(1); // One parameter
add(1.2); // Two parameters
add(new Integer[]{1.2.3.4}); // Pass the array
Copy the code