Java Foundation 7--Constructors--this--static Memory __java

Source: Internet
Author: User
Tags first row
7-1, Constructors-Overview

1, Features:

(1) The function name is the same as the class name.

(2) The return value type is not defined.

(3) There is no specific return value.

2, constructors

Constructors are constructs that create objects that are called functions.

3, function

You can initialize an object, meaning that it contains some content as soon as it is created.

4, Example:

Class person{
	private String name;
	private int age;
	Person () {	//define an empty parameter constructor
		Sop ("person run ...");
	public void Speak () {
		SOPs (name+ "::" +age)
class Demo {public
	static void Main (string[] args) {person
		p = new Person ();
7-2, default constructor

1, the creation of objects must be initialized through constructors.

2, if a constructor is not defined in a class, there must be a default null parameter constructor in the class, and if the specified constructor is defined in the class, then the default constructor in the class is not.

3, constructors are used to initialize objects, and objects that are not initialized are never used.

7-3, the difference between a general function and a constructor


(1) Constructor: When an object is created, it invokes the corresponding constructor and initializes the object.

Generic function: When an object is created, it is used when functional functions are required.

(2) Constructor: The object is called when it is created, and is called only once.

Generic function: When an object is created, it can be invoked multiple times.

7-4, constructor-overload

1, when the constructor is defined.

When you describe something, it already exists and has something that is defined in the constructor.

2, Overload: The function name is the same, the argument list is different.


Class Person {
	private String name;
	private int age;
	Person () {		//function 1
		name = "Baby";
		Age = 1;
	Person (String N) {	//function 2
		name = n;
	Person (String N,int a) {//function 3
		name = N;
		age = A;
	public static void Main (string[] args) {person
		p1 = new Person ();		Call function 1 person
		p2 = new Person ("Zhangsan");	Call function 2 person
		p3 = new Person ("Lisi");	Call function 3

3, attention, shape like:

person (int a,string n);

Person (String n,int a);

The two functions are overloaded forms.

7-5, constructor-memory diagram

Person p = Newperson ("Lisi", 20);

P.speak ();

The above two sentences are expressed in memory as follows:


(1) Starting from the main function, the main function into the stack, local variable p into the stack.

(2) Create the entity of P in the heap, assign the address, and initialize the variable by default.

(3) The new person ("Lisi", 20), invokes the constructor of the person, passes the arguments in, the person (string,int) function into the stack.

(4) Assign the passed parameter to the value.

(5) Person P = Newperson ("Lisi", 20); When executed, the address value is assigned to the p,p in the stack pointing to the entity in the heap.

(6) Person (string,int) execution completed, stack.

(7) P.speak (); Call speak method, speak () into stack.

(8) Execute the OUTPUT statement in the speak.

(9) Speak () execution, stack.

7-6, constructors-Details

1, constructor: Person (String N) {name=n;}

With the general function public void SetName (String n) {name= n;}

No conflict, the constructor is assigned at the beginning of the creation of the object, only once, the value can not be changed, the general function can be called more than once, you can change the value later.

2, the constructor can call the general function, in general function does not call the constructor, constructor is used to initialize the object, if you want to call the constructor in a general function, you need to create a new object.

3,person () {} is not the same as Voidperson () {}, the former is a constructor, the latter is a general function, the constructor plus modifier becomes a general function, and the general function can be the same as the class name.

4, if the constructor is already defined in the person class, the default constructor is already overwritten, and if there is only one void person () {}, and the person P = new person () in main, the compilation fails because the Voidperson () {} is a general function The primary function cannot find the person () {} to initialize the object, so it is reported as an error.

5, there is a return statement in the constructor, the return statement is used to end the function, and if there is a statement behind it, compile the error, because the statement following the back will not be executed.

7-7, keyword-this usage scenario-memory diagram

1,this represents the object's * * *, such as representing the object's name attribute.

2, Scene: When the member variable and local variable duplicate name, you can use the keyword this to differentiate.

3,this: Represents an object that represents the current object.

This is the reference to the object to which the function belongs.

To put it simply: which object calls the function where this is, this represents which object.

For example:

Class Person {
	private String name;
	Person (String name) { = name;
	public static void Main (string[] args) {person
		p = new Person ("Zhangsan");

This in the example above refers to the P object, which to the Name property of this object in heap memory.

4, Memory diagram:

Class person{
	private String name;
	private int age;
	Person (String name) { = name;
	public void Speak () {
		SOP (name + ': ' + age);
Class Thisdemo {public
	static void Main (string[] args) {person
		p = new Person ("Zhangsan");
		P.speak ();


(1) Starting from the main function, the main function into the stack, local variable p into the stack.

(2) New person ("Zhangsan"); creates space in heap memory, assigns addresses, name and age variables into objects in the heap, defaults to null and 0.

(3) The person (name) constructor is in the stack.

(4) The "Zhangsan" is passed in and assigned to the local variable name.

(5) The function entry stack automatically comes with a this reference, because P calls person (), so the value of this is the address 0x0078 of the newly created object.

(6) This in person refers to the 0x0078 in the heap.

(7) points to name in 0x0078 and assigns this name to "Zhangsan".

(8) The person (name) is executed and the stack is loaded.

(9) p = Newperson ("Zhangsan"); Assign 0x0078 to P in main.

(ten) Speak () function into the stack, and bring a this reference.

(one) P.speak ();p call speak and give the address of P to this.

(12) Finish the output stack.

Description: In fact, each function comes with a this, but not the same name without distinction, the duplicate name with this to distinguish, this refers to the current object's address.

such as: SOP (name + age), the standard wording is: SOP ( + this.age);

7-8,this keyword Usage scenarios and details

1, calling the constructor in the constructor

Person (String name) { = name;
Person (String Name,int age) {This
	(name);	This represents the object, initializes the object, and invokes the constructor This.age = Age in the same class.

This can also be used to invoke other constructors in the constructor.

Note: Only the first row of the constructor can be defined because the initialization action is to be performed first. This is the Java syntax, do not write an error.

2, sample code memory diagram:

Class person{
	private String name;
	private int age;
	Person () {
		name = "Baby";
		Age = 1;
		SOP ("person run ...");
	Person (String name) { = name;
	Person (String Name,int age) {This
		This.age = age;
	public void Speak () {
		sop ( + "-" + This.age);
Class Thisdemo {public
	static void Main (string[] args) {person
		p = new Person ("Zhangsan");
		P.speak ();


(1) Starting from the main function, the main function into the stack, local variable p into the stack.

(2) Newperson ("Zhangsan", 30); Open memory space in the heap, assign addresses, name and age are initialized to null and 0 by default.

(3) Pass the parameter, person (name,age) into the stack, with this reference, point to heap memory 0x0067, local variable name,age pass parameter assignment.

(4) This (name) call person (name), with this reference, points to the heap memory 0x0067, and the local variable name is assigned a value.

(5) = name is assigned to the member variable name of the entity in the heap by name.

(6) Person (name) runs through the stack.

(7) This.age=age in the execution person (name,age), assigning a value to a member variable in the heap.

(8) Person (name,age) run the stack.

(9) Assign the 0x0067 to P in main.

3, to avoid the following cases of the program:

Class person{
	private String name;
	private int age;
	Person () {This
		("haha");//2. Call person (name)   4. Call person (name) ....
		Name = "Baby";
		Age = 1;
		SOP ("person run ...");
	Person (String name) {this
		();//3. Call person ()    5. Call person () .... = name;
	public static void Main (string[] args) {
		new person ();  1. Initialize to person, call person ()

The above code is called back and forth between person () and person (name), causing stack memory to overflow.

7-9,this Application

Procedures: To determine whether the peer

Public Person {
	private String name;
	private int age;
	Person () {} person
	(String name,int age) { = name;
		This.age = age;
	public static void Main (string[] args} {person
		p1 = new Person ("AA");
		person P2 = new person ("BB");
		Boolean B = (p2);
		System.out.println (b);
	public static Boolean compare (person p) {/
		* method One
		if (this.age = = p.age) {return
		} else {
			re Turn false;
		//Method two return
		this.age = = P.age

7-10,static keywords-data sharing

Data that is decorated with static is data that can be shared.

such as: String name;

staticstring country = "cn";

Since everyone's name is not the same, but country, are the CN, if the CN is not defined as static, when each created an object, each object will have a CN, wasting memory space.

Country can be defined as static so that all objects can share this data, which object needs to be called.

Characteristics of 7-11,static

1, the members decorated with static are preceded by objects, exist in the class, and can be called directly with the class name. such as;

2, not all are defined as static, some can be shared, but some are unique to each object and cannot be shared.

3, Features:

(1) Static is a modifier that is used to modify a member.

(2) The members of the static modifier are shared by all objects.

(3) static takes precedence over the existence of an object because the members of the static modifier already exist as the class is loaded.

(4) Static decorated members of a more than one invocation, can be directly called by the class name, format: class name. static members.

(5) The static-decorated data is shared data, and the object stores the unique data.

7-12, the difference between a member variable and a static variable

Class person{
	string name;//member variable, instance variable
	static string country = "CN";//static variable, class variable


(1) The life cycle of two variables is different.

Member variables: As objects are created, they are released as objects are recycled.

Static variables: exist as classes are loaded, disappearing as classes disappear.

(2) different ways of calling.

Member variable: can only be invoked by an object.

Static variables: Can be invoked by an object or by a class name.

(3) The alias is different.

Member variables: also become instance variables.

Static variables: also become class variables.

(4) The data storage location is different.

Member variables: The data is stored in the object of the heap memory, so it is also called the object's unique data.

Static variables: Data is stored in the static area of the method area (the shared data area), so it is also called the shared data of the object.

7-13,static Matters of note

1, note:

(1) Static methods can access only static members. (Non-static can access both static and non-static).

(2) This or Super keyword may not be used in static methods. (because static is loaded first, there is no object, you cannot use this)

(3) The main function is static.

2,main () is static and can not call non-static methods directly, by creating an object invocation.

Non-static variables omit this before they are used, and the class name is omitted before the static variable is used.

Class person{public
	static void Main (string[] args) {
		run ();//run must be static, otherwise the error
	} public
	static void run ( {
		System.out.println ("Run ...");
7-14,main function Detailed

1,public static void Main (string[] args)

The special of the main function:

(1) The format is fixed.

(2) Recognized and invoked by the JVM.

Public: Because permissions must be maximum.

Static: The program starts with the main function and does not require the object to invoke the main function, which is directly invoked by the class name of the main function, so it must be static

For example, to run the person class, we typically enter Java person execution at the command line, and in fact the JVM invokes the Java Person.main.

void: The main function does not have a specific return value.

Main: The function name, not the keyword, is just a fixed name recognized by the JVM.

String[] args: This is the argument list for the main function, which is a parameter of a string array type.

2, when you call the main function, you also pass the arguments to the String[]args, which is passed by the JVM.

You can use System.out.println (args) to verify that the result is:


Can be described as an array of strings.

The default length of this array is 0.

The JVM passes the newstring[0] args to string[].

3, when we run the program, we can pass parameters to the main function, any results in the program will eventually be turned into a string to display on the screen.

4, run the program newsletters value, the command line, when using the Java command to pass.

The Java person haha hehe xixi is separated by a space and passed to args as an element in the array.

The args in 5,string[] can be changed, not fixed, and args is a shorthand for arguments.

6,public static void Main (string[] args)

publicstatic void Main (int[] x)

The two are not conflicting, are overloaded form.

If the subsequent int[] x changes to String[]x, the conflict occurs.

7-15,static Keywords-Program memory detailed

Take the following procedure as an example:

Class person{
	private String name;
	private int age;
	static String country = "cn";
	Public person (String Name,int age) { = name;
		This.age = age;
	public void Show () {
		System.out.println ( + ":" + + ":" + this.age);
	public static void Method () {
		System.out.println (;
Class staticdemo{public
	static void Main (string[] args) {
		person.method ();
		Person p = new person ("Java"); ();

When running this program in Java staticdemo on the command line, the class is loaded into memory, space is opened up, and the method area is divided into two areas of static and non-static areas.


(1) When executing Staticdemo, the Staticdemo class is loaded into memory and space is opened, and the default constructor Staticdemo () is also loaded into memory and loaded into the non-static area of the method area of the memory.

(2) Then the main function also goes into memory, the static area that enters the memory method area (the method of the static area and the Non-static area are shared, the only difference being that the encapsulated data is different), and all members of the Non-static zone have a this owning, because the method of the Non-static area is called by the object, The static zone method is the name of the class to which it belongs.

(3) When the Java Staticdemo, carriage return, the function loaded, Staticdemo directly with the class name call the main function, when the main function into the stack, the main function of all the code in the static section of the main ().

(4) Run Person.method (), when the person class is used, then the person loads, At this time the JVM will find out if there are person.class files in the classpath, if not in the current default directory to find, found will be person.class loaded into memory, the person class constructor person (name,age) and the Code and void Show () methods and the code in them are loaded into the non-static zone; static method methods () and static variables country in person are loaded into the static area, country default is initialized to NULL because the value is assigned to "CN", So immediately show initialized to CN, now COUNTRY=CN.

(5) Person.method (); is called with the class name, description method () is static, call directly in the static area of the person class to find methods, found, method methods into the stack, note that this method is not belong to this, Only non-static zones hold this.

Description: Method methods in the method area, why the stack execution.

Because the method area is the storage area of the method, also called the method table, all the methods are here. And the stack is the operation area, because the method may have local variables, local variables need to be in the stack memory to open up space storage, and run the local variable to release, so to run to the stack. But the System.out.println () method does not go into the stack, this method is for output, there are no local variables. In the stack, only the local variables of the method are stored, and the method is implemented after the stack, because there is only one System.out.println () method, so the System.out.println () execution is found directly into the static region's methods. There are local variables to open space in the stack.

There is in the sop of method methods, where the country is found directly from the person class in the static area, and the corresponding value is output.

(6) Method methods to run the stack.

(7) Execute person p = new person ("Java", 20); local variable p into stack.

(8) Open space for P objects in the heap, assign addresses, member variables name,age into memory, initialize to null and 0 by default, and then perform constructor initialization, where constructor person (name,age) goes into the stack to initialize data in the object, The function holds a this reference, and the value is 0x0078, because the 0x0078 object calls it, and the local variable name is assigned to the Java,age is assigned a value of 20, since the person (name,age) is in the stack and initialized, the code in the method area begins to execute ( Person (name,age) method, so this represents 0x0078, so we find name in the heap from this address and assign it to Java, assigning 20 to age.

(9) Person (name,age) run complete, stack.

(a) New person ("Java", 20); initialization completes, assigning address 0x0078 to p,p pointing to heap memory.

(one) (); Show method into the stack, because it is non-static, with a This reference, this points to 0x0078. A country in show has a class name that is already in the Sop,sop, is called directly in the person class in the static area, and the name and age are omitted this,this is this in show, representing 0x0078, So print the name and age of 0x0078, Java and 20, and then output.

(12) Output finished, Show method execution completed, stack.

(13) Execution to return statement in main function, end of main function, main function stack, end of program execution, end of JVM. when will the 7-16,static keyword be used?

static when to use.

1, static variables

When the value of the member variable in the parse object is the same, the member can be decorated statically. As long as the data is different in the object, is the object's unique data, must be stored in the object, Non-static. If the same data, the object does not need to be modified, only need to use it, do not need to store in the object, defined as static.

2, static function

Whether the function is statically decorated is a reference to whether the function has access to the unique data in the object. To put it simply, from the source, the feature needs to access non-static member variables, which, if needed, are non-static and can be defined as static if not required. Of course, it can also be defined as non-static, but it is not statically required to be invoked by an object, and the creation of an object calls a method that is not static and does not have access to the unique data, and that object creation is meaningless.

7-17,static Static code block

Static code blocks are executed as the class is loaded, and are loaded from this class to extinction, only once.

Function: You can initialize a class.


Class Person {
	static {

Application: Not all classes are initialized with constructors. If the method in a class is all static, then there is no need to create the object, there is no new process without creating the object, the constructor cannot be initialized without new, and the class can be initialized with static code blocks.

7-18, building blocks of code

1, the construction code block is defined in the class and it can initialize all objects, that is, each time a new object is executed.

2, the difference between the construction code block and the local code block

The construction code block is defined in the class, and the local code block is defined in the method body.

3, Format:

Class Person {
		//Construction code block ...
		Extracts the initialization content of all objects in common, defined here.
		//each time a person object is created, this block of code executes.

4, program execution order

Static code block--> Construction code block--> constructor

7-19, Summary

1, the members that are modified by static have the following characteristics:

(1) loading as the class is loaded.

(2) takes precedence over the object.

(3) is shared by all objects.

(4) can be directly invoked by the class name.

Note When using 2,static:

(1) Static methods can access only static members.

(2) The static method can not write This,super keyword.

(3) The main function is static.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.