Detailed explanation of static static in Java!

I. Overview

Static means "static" and can be used to modify member variables and member methods.

The main function of static is to create domain variables or methods independent of specific objects

Simple understanding :

  • The method or variable modified by the static keyword does not need to depend on the object for access, as long as the class is loaded, it can be accessed through the class name.
  • And will not create multiple copies of data in memory due to multiple creation of objects

2. Analysis

Generally speaking, when we are creating a class, we are describing the appearance and some behaviors of the objects of that class; generally, we need to create objects of that class with new, otherwise, we don't actually get any objects. When we execute new to create an object, the data space can be allocated and internal methods can be called externally!
To make it easier to understand, let’s draw a picture and say emmmmmmm
figure 1

class Person{
    
    
	String name;
	static string region;
}

Person p = new Person();

When we create a class Person{}, it is stored in the method area. When new Person(); we open up a new memory space in the heap memory! The object p is stored in the stack memory and used to store the address of the space created in the heap memory. At this time, if a static property is created in the class, we continue to draw! !

figure 2

class Person{
    
    
	String name;
	static string region;
}

Person p1 = new Person();

Person p2 = new Person();

You can see that statically modified properties are in the method area (understand: properties created by non-static methods can be understood as properties of objects, properties created by static methods are properties of classes) static properties are shared.

to sum up

When a thing is declared as static, it means that the and or method will not be associated with any object instance of the class that contains it. So even if you have never created any object of a certain class, you can call its static method or access its static domain. Usually, you must create an object and use it to access data or methods. Because non-static fields and methods must know the specific object they work with! ! !

Focus:

  1. Static members are loaded and initialized when the class is loaded.
  2. No matter how many objects exist in a class, static properties will always have only one copy in memory (it can be understood as common to all objects)
  3. When accessing: Static cannot access non-static, non-static can access static!

Guess you like

Origin blog.csdn.net/weixin_43515837/article/details/110247097