Home Java Javagetting Started When are java classes loaded?

When are java classes loaded?

Nov 13, 2019 am 11:36 AM
java

When are java classes loaded?

When is the class loaded?

The loading of the class is completed through the class loader (Classloader), which can be either Chinese-style [eagerly load] (loading as long as other classes reference it) loads a class, or it can be lazy load [lazy load] (wait until class initialization occurs before loading). (Recommended learning: java course)

But I believe this is related to different JVM implementations, but it is guaranteed by JLS (only when there is a static initialization requirement be loaded).

When is the class initialized?

After the class is loaded, the initialization of the class will occur, which means that it will initialize all class static members. A class is initialized in the following situations :

Instances are created by using the new() keyword or using class.forName() reflection, but it may cause ClassNotFoundException.

The static method of the class is called

The static field of the class is assigned

The static field is accessed, and it is not a constant

Executed in the top-level class assert statement

Reflection can also initialize a class, such as certain methods under the java.lang.reflect package. JLS strictly states: a class will not be initialized for any reason other than the above.

How a class is initialized

Now we know when the initialization of a class is triggered, it is precisely written in the Java Language Specification. But understand clearly the fields (fields, static or non-static), blocks (static or non-static), different classes (subclasses and superclasses) and different interfaces (subinterfaces, implementation classes and superinterfaces) The order of initialization is also important for classes.

In fact many core Java interview questions and SCJP questions are based on these concepts. Here are some rules for class initialization:

Class initialization in order from top to bottom , so fields declared at the top are initialized earlier than fields at the bottom

Super classes are initialized earlier than subclasses and derived classes

If the initialization of a class is triggered by accessing a static field, then Only the class that declares the static field is initialized, and does not trigger the initialization of the superclass or the initialization of the subclass even if the static field is referenced by a subclass or subinterface or its implementation class.

Interface initialization will not cause the initialization of the parent interface.

The initialization of static fields is during the static initialization of the class, and the initialization of non-static fields is during the creation of instances of the class. This means that static fields are initialized before non-static fields.

Non-static fields are initialized through the constructor. The constructor of the subclass will implicitly call the constructor of the parent class before doing any initialization. It ensures that non-static or instance variables (parent class) are initialized earlier than the child. kind

The above is the detailed content of When are java classes loaded?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1545
276
How to send and receive messages over a WebSocket in Java How to send and receive messages over a WebSocket in Java Aug 16, 2025 am 10:36 AM

Create a WebSocket server endpoint to define the path using @ServerEndpoint, and handle connections, message reception, closing and errors through @OnOpen, @OnMessage, @OnClose and @OnError; 2. Ensure that javax.websocket-api dependencies are introduced during deployment and automatically registered by the container; 3. The Java client obtains WebSocketContainer through the ContainerProvider, calls connectToServer to connect to the server, and receives messages using @ClientEndpoint annotation class; 4. Use the Session getBasicRe

How to configure logging in a Java application? How to configure logging in a Java application? Aug 15, 2025 am 11:50 AM

Using SLF4J combined with Logback or Log4j2 is the recommended way to configure logs in Java applications. It introduces API and implementation libraries by adding corresponding Maven dependencies; 2. Get the logger through the LoggerFactory of SLF4J in the code, and write decoupled and efficient log code using parameterized logging methods; 3. Define log output format, level, target (console, file) and package level log control through logback.xml or log4j2.xml configuration files; 4. Optionally enable the configuration file scanning function to achieve dynamic adjustment of log level, and SpringBoot can also be managed through Actuator endpoints; 5. Follow best practices, including

How to deploy a Java application How to deploy a Java application Aug 17, 2025 am 12:56 AM

PrepareyourapplicationbyusingMavenorGradletobuildaJARorWARfile,externalizingconfiguration.2.Chooseadeploymentenvironment:runonbaremetal/VMwithjava-jarandsystemd,deployWARonTomcat,containerizewithDocker,orusecloudplatformslikeHeroku.3.Optionally,setup

XML Data Binding with Castor in Java XML Data Binding with Castor in Java Aug 15, 2025 am 03:43 AM

CastorenablesXML-to-Javaobjectmappingviadefaultconventionsorexplicitmappingfiles;1)DefineJavaclasseswithgetters/setters;2)UseUnmarshallertoconvertXMLtoobjects;3)UseMarshallertoserializeobjectsbacktoXML;4)Forcomplexcases,configurefieldmappingsinmappin

phpMyAdmin security best practices phpMyAdmin security best practices Aug 17, 2025 am 01:56 AM

To effectively protect phpMyAdmin, multiple layers of security measures must be taken. 1. Restrict access through IP, only trusted IP connections are allowed; 2. Modify the default URL path to a name that is not easy to guess; 3. Use strong passwords and create a dedicated MySQL user with minimized permissions, and it is recommended to enable two-factor authentication; 4. Keep the phpMyAdmin version up to fix known vulnerabilities; 5. Strengthen the web server and PHP configuration, disable dangerous functions and restrict file execution; 6. Force HTTPS to encrypt communication to prevent credential leakage; 7. Disable phpMyAdmin when not in use or increase HTTP basic authentication; 8. Regularly monitor logs and configure fail2ban to defend against brute force cracking; 9. Delete setup and

Excel autofill not working Excel autofill not working Aug 15, 2025 pm 01:19 PM

EnsureAutoFillisenabledbychecking"Enablefillhandleandcelldrag-and-drop"inFile>Options>Advanced;2.Correctlyusethefillhandle—thesmallsquareatthebottom-rightoftheselectedcell—draggingwiththeblackpluscursor,notthewhitearrow;3.Unmergecells

You are not currently using a display attached to an NVIDIA GPU [Fixed] You are not currently using a display attached to an NVIDIA GPU [Fixed] Aug 19, 2025 am 12:12 AM

Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

What is the assert keyword in Java? What is the assert keyword in Java? Aug 17, 2025 am 12:52 AM

TheassertkeywordinJavaisusedtovalidateassumptionsduringdevelopment,throwinganAssertionErroriftheconditionisfalse.2.Ithastwoforms:assertcondition;andassertcondition:message;withthelatterprovidingacustomerrormessage.3.Assertionsaredisabledbydefaultandm

See all articles