java object-oriented foundation static

static properties can be called directly by the class name.

After static is defined, it can be understood as a global variable.

 

E.g:

class Preson{
	static String name = "AAAAA";
	public void info() {
		System.out.println(this.name);
	}
}
public class static01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		////////////before fixing//////////////////////////////
		
		Preson preson01 = new Preson ();
		Preson preson02 = new Preson ();
		Preson preson03 = new Preson ();
		preson01.info();
		preson02.info();
		preson03.info();
		preson03.name = "BBBBBBB";
		////////////////modified //////////////////////
		preson01.info();
		preson02.info();
		preson03.info();
	}

}

  output:

  

AAAAA
AAAAA
AAAAA
BBBBBBB
BBBBBBB
BBBBBBB

Multiple instantiations, only one of them is modified, and all the others are modified, indicating that this property is shared by all objects.

Each object has its own stack space, and the stack controls save the properties of their respective objects, but after the static declaration, they are stored in the global data area. The above objects all point to the same content in the global data area, so a modification After that, the content of all objects changes. It is best to call it in the form of "class name.property". Do not modify directly with the instantiated object.

static can also be used to declare a method. After the declaration, it can be called directly by the method of "class name. method", but pay attention:

  Notice:

    Using static methods You cannot call non-static properties or methods. Because non-static properties or methods are generated only after instantiation, and static properties or methods can be called directly without instantiation.

static related applications:

  1. It can be used to count how many objects a class has generated, because when an object is instantiated, there will be a constructor.

class static application class {
	static int number = 0;
	public static application class() {
		number++;
	}
}
public class static application {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new static application class();
		new static application class();
		new static application class();
		System.out.println(static application class.number);//Output 3
           } }

  

There are 4 memory areas in JAVA:

  Stack memory: can save the name of the object (save the address of accessing the heap memory)

  Heap memory: holds the specific properties of each object.

  Global data area: holds properties of static type. (commonly useful)

  Global code area: holds the definitions of all methods.

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324904562&siteId=291194637