Home  >  Article  >  Java  >  How objects are initialized in Java

How objects are initialized in Java

王林
王林Original
2019-11-21 16:14:023158browse

How objects are initialized in Java

The process of object initialization:

1: Initialization class

When you first create an object:

Dog dog = new Dog();

When you access a static method or static field of a class for the first time:

Dog.staticFields;

The Java interpreter will look for the path of the class and locate the compiled Dog.class file.

Two: Obtain class resources

Then jvm will load Dog.class and generate a class object. At this time, if there are static methods or variables, the static initialization action will be executed. Please note at this time that static initialization will only be run once when the Class object is loaded for the first time during the running of the program. These resources will be placed in the method area of ​​jvm.

The method area is also called the static area. Like the heap, it is shared by all threads.

The method area contains elements that are always unique in the entire program, including all class and static variables.

3: Initialize the object Dog dog = new Dog()

1. When creating a Dog object for the first time, perform the above steps one or two first

2. Allocate enough storage space for the Dog object on the heap. All properties and methods are set to default values ​​(numbers are 0, characters are null, Boolean is false, and all references are set to null. )

3. Execute the constructor to check whether there is a parent class. If there is a parent class, the constructor of the parent class will be called first. It is assumed here that Dog has no parent class, and the assignment of the default value field, which is the initialization action of the method, is executed.

4. Execute the constructor.

Recommended tutorial: Getting started with java development

The above is the detailed content of How objects are initialized in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn