Class variables and methods in java

One, class variables

1. Static code block static{}

The static code block will only be executed once;

2. When the class is defined, the variables in the class are created in the code area, and the static code block will be automatically executed at this time;

3. Class variables are the only variables shared by all objects in the class. If a class variable is also defined as a public type, then other classes can also use this variable, and because the memory space of the class variable is allocated when the class is defined, there is no need to generate this variable when referencing this variable. The object of the class, but directly use the class name to point to it.

4. Class method
If you need to use the program code that references it without creating an object instance, then mark the method with the keyword static.
If you call from other methods in the current class, you can write the method name directly.
Note: (1) Since a static method can be used without defining the object of the class to which it belongs, there is no this value.
Therefore, a static method can use its internally defined parameters or static variables.
(2) Static methods cannot be rewritten
(3) Static methods cannot call non-static methods It
will happen: Non-static method "..." cannot be referenced from a static context
Example:

package smm;

public class LearnStatic {

static int  i=1;
static{//静态代码块只会被执行一次
	System.out.println("a");
	i++;
}
public LearnStatic(){
	System.out.println("b");
	i++;
}

public static void main(String[] args) {
	// TODO Auto-generated method stub
	LearnStatic l1=new LearnStatic();
	System.out.println(l1.i);

	LearnStatic l2=new LearnStatic();
	System.out.println(l2.i);

}

}
Output result:

a

b
3
b
4

3. The difference between class variables and instance variables

(1) Class variables belong to classes, can be shared, and belong to public attributes; instance variables belong to an individual object;

(2) Add static as a class variable or static variable, otherwise it is an instance variable;

Two, class method

Similar to class variables, from variables to methods.

Original link

Guess you like

Origin blog.csdn.net/weixin_45773632/article/details/109464313