[Java Study Notes] java language core-object-oriented static keywords, learning notes static
- Modified members have the following features:
- Usage notes
- Differences between instance variables (member variables) and class variables (static variables)
Member variables exist with the creation of objects and are released with the collection of objects;
Static variables exist as the class is loaded and disappear as the class disappears.
2. Different call Methods
Member variables can only be called by objects
Static variables can be called by objects or by class names (class names are generally recommended)
3. different aliases
A member variable is also called an instance variable.
Static variables are also called class variables.
4. Different data storage locations
The member variable data is stored in the object in the heap memory, so it is the special data of the object.
Static variable data is stored in the static area of the Method Area (data area or shared data area), so it is also called the shared data of objects.
Run the following code in the memory:
class Person{ private String name; private int age; static String country = "CN"; public Person(String name, int age){ this.name = name; this.age = age; } public void show(){ System.out.println(Person.country+":"+this.name+":"+this.age); } public static void method(){ System.out.println(Person.country); }}class StaticDemo2{ public static void main(String[] args){ Person.method(); Person p = new Person("java",20); p.show(); }}
Memory diagram:
Note:
Static {System. out. println ("this is a static code block ");}
1. Static code block
It is executed once as the class is loaded. Class.
2. Role
Class initialization. For example, all the Math classes provided by Java APIs are static methods and object creation is not allowed. At this time, constructors cannot be used for initialization, because constructors generally initialize objects, objects cannot be created. Therefore, static code blocks must be used for initialization.
Unlike static code blocks, a code block belongs to a class, for example:
Class Demo {System. out. println ("this is the Construction Code block ");}
//。。。}
Related to objects
All objects can be initialized. constructors initialize the objects accordingly.
It is executed every time an object is created. Static code blocks are executed once during class loading.