search
HomeJavajavaTutorialWhat are the details of using Java code blocks?

1. Basic introduction

The code block is also called the initialization block, which is a member of the class (part of the class). It is similar to a method. The logical statement is encapsulated in the method body and hugged with {} ;

But unlike methods, there is no method name, no return, no parameters, only the method body, and there is no need to explicitly call it through an object or class.

Basic syntax

(modifier)(optional){code};

Note:

1. Modifiers are optional. If you want to write, you can only write static

2. Code blocks can be divided into two categories. Those modified with static are called static code blocks, and those without static modification are called ordinary code blocks.

3.; Optional

Benefits

1. Equivalent to another form of constructor, which can perform initialization operations

2 .If there are repeated statements in multiple constructors, they can be extracted into code blocks.

Quick Start

package com.demo.codeblock_;
public class codeblock01 {
    public static void main(String[] args) {
        movie m01=new movie("环太平洋");
        movie m02=new movie("荒野大飞",66);
        movie m03=new movie("无暇赴死",55,"老K");
    }
}
class movie{
    private String name;
    private double price;
    private String director;
    {
        System.out.println("电影屏幕打开。。。");
        System.out.println("广告开始。。。");
        System.out.println("电影开始。。。");
    }
    //三个构造器重载
    public movie(String name) {
//        System.out.println("电影屏幕打开。。。");
//        System.out.println("广告开始。。。");
//        System.out.println("电影开始。。。");
        System.out.println("构造器movie(String name)被调用。。。");
        this.name = name;
    }
    public movie(String name, double price) {
        //        System.out.println("电影屏幕打开。。。");
//        System.out.println("广告开始。。。");
//        System.out.println("电影开始。。。");
        System.out.println("构造器movie(String name, double price)被调用。。。");
        this.name = name;
        this.price = price;
    }
    public movie(String name, double price, String director) {
        //        System.out.println("电影屏幕打开。。。");
//        System.out.println("广告开始。。。");
//        System.out.println("电影开始。。。");
        System.out.println("构造器movie(String name, double price, String director)被调用。。。");
        this.name = name;
        this.price = price;
        this.director = director;
    }
}

What are the details of using Java code blocks?

2. Code block details

Code block usage precautions and detailed discussion

1 ) static code block is also called static code block. Its function is to initialize the class, and it is executed as the class is loaded, and will only be executed once. If it is an ordinary code block, it will be executed every time an object is created.

2) When is the class loaded [Important!]

①When creating an object instance (new)

②When creating a subclass object instance, the parent class will also be loaded

③When using static members of the class (static properties, static methods)

Case demonstration: Class A extends the static block of class B

3) Ordinary code block, It is called implicitly when creating an object instance. Once created, it will be called once. If you only use static members of the class, the ordinary code block will not be executed.

package com.demo.codeblock_;
public class codeblock02 {
    public static void main(String[] args) {
        //类被加载的情况举例
        //1.创建对象时new
        //AA aa=new AA();
        //2.创建子类对象实例,父类也会被加载,而且,父类先被加载,子类后被加载
        AA aa01=new AA();
        //3.使用类的静态成员时
        System.out.println(cat.n);
        DD d1=new DD();
        DD d2=new DD();
    }
}
class DD{
    static {
        System.out.println("DD的静态代码被执行1次");
    }
}
class animal{
    static {
        System.out.println("animal的静态代码被执行");
    }
}
class cat extends animal{
    public static int n=888;
    //静态代码块
    static {
        System.out.println("cat的静态代码块被执行");
    }
}
class BB {
    static {
        System.out.println("BB的静态代码被执行");
    }
}
class AA extends BB{
    static {
        System.out.println("AA的静态代码被执行");
    }
}

What are the details of using Java code blocks?

Class calling sequence

When creating an object, in a class calling sequence: (Key points, difficulties)

①Call Static code blocks and static property initialization (Note: Static code blocks and static property initialization calls have the same priority. If there are multiple static code blocks and multiple static variable initializations, they will be called in the order they are defined)

②Call the initialization of ordinary code blocks and ordinary attributes (Note: The priority of ordinary code blocks and ordinary attribute initialization calls is the same. If there are multiple ordinary code blocks and multiple non-ordinary attribute initializations, they will be called in the order defined)

③Call the constructor method.

Example

package com.demo.codeblock_;
public class codeblock03 {
    public static void main(String[] args) {
        A a=new A();
    }
}
class A{
    public A(){
        System.out.println("A的无参构造被调用");
    }
    int n2=getn2();
    {//普通代码块
        System.out.println("A的普通代码块被调用");
    }
    int getn2(){
        System.out.println("getn2被调用");
        return 99;
    }
    private static int n=getn();
    static {
        System.out.println("A的静态代码被调用");
    }
    public static int getn(){
        System.out.println("getn被调用");
        return 100;
    }
}

What are the details of using Java code blocks?

Code block details 2

The front of the constructor actually implies super(and calls ordinary code blocks, Write a new class to demonstrate statically related code blocks and attribute initialization. When the class is loaded, it will be executed

, so it will be executed before the constructor and ordinary code blocks

class A {
public AO{
super0:
//调用普通代码块
_System.out.println("ok");
}
}

Example

package com.demo.codeblock_;
public class codeblock04 {
    public static void main(String[] args) {
        B b=new B();
    }
}
class AA{
    {
        System.out.println("AA的普通代码块");
    }
    public AA(){
        //1.super()
        //2.调用本类的普通代码块
        System.out.println("AA的构造器被调用");
    }
}
class B extends AA{
    {
        System.out.println("B的普通代码块");
    }
    public B(){
        //1.super()
        //2.调用本类的普通代码块
        System.out.println("B的构造器被调用");
    }
}

What are the details of using Java code blocks?

Code block details 2

Let’s take a look at when creating a subclass object (inheritance relationship), their static code blocks, static property initialization, ordinary Code block, ordinary attribute initialization, and constructor calling sequence are as follows:

1. The static code block of the parent class and the static properties (the priority is the same, hot-line in the order of definition

2. Child Static code blocks and static attributes of the class (same priority, executed in the order of definition)

3. Ordinary code blocks and ordinary attribute initialization of the parent class (same priority, executed in the order of definition)

4. Construction method of parent class

5. Ordinary code block and ordinary attribute initialization of subclass (same priority, executed in the order of definition)

6.Construction method of subclass

7. Static code blocks can only directly call static members (static properties and static methods), and ordinary code blocks can call any members.

Example

package com.demo.codeblock_;
public class codeblock05 {
    public static void main(String[] args) {
        //老师说明
        //(1) 进行类的加载
        //1.1 先加载 父类 A02 1.2 再加载 B02
        //(2) 创建对象
        //2.1 从子类的构造器开始
        //new B02();//对象
        new C02();
    }
}
class A02 { //父类
    private static int n1 = getVal01();
    static {
        System.out.println("A02的一个静态代码块..");//(2)
    }
    {
        System.out.println("A02的第一个普通代码块..");//(5)
    }
    public int n3 = getVal02();//普通属性的初始化
    public static int getVal01() {
        System.out.println("getVal01");//(1)
        return 10;
    }
    public int getVal02() {
        System.out.println("getVal02");//(6)
        return 10;
    }
    public A02() {//构造器
        //隐藏
        //super()
        //普通代码和普通属性的初始化......
        System.out.println("A02的构造器");//(7)
    }
}
class C02 {
    private int n1 = 100;
    private static  int n2 = 200;
    private void m1() {
    }
    private static void m2() {
    }
    static {
        //静态代码块,只能调用静态成员
        //System.out.println(n1);错误
        System.out.println(n2);//ok
        //m1();//错误
        m2();
    }
    {
        //普通代码块,可以使用任意成员
        System.out.println(n1);
        System.out.println(n2);//ok
        m1();
        m2();
    }
}
class B02 extends A02 { //
    private static int n3 = getVal03();
    static {
        System.out.println("B02的一个静态代码块..");//(4)
    }
    public int n5 = getVal04();
    {
        System.out.println("B02的第一个普通代码块..");//(9)
    }
    public static int getVal03() {
        System.out.println("getVal03");//(3)
        return 10;
    }
    public int getVal04() {
        System.out.println("getVal04");//(8)
        return 10;
    }
    //一定要慢慢的去品..
    public B02() {//构造器
        //隐藏了
        //super()
        //普通代码块和普通属性的初始化...
        System.out.println("B02的构造器");//(10)
        // TODO Auto-generated constructor stub
    }
}

What are the details of using Java code blocks?

The above is the detailed content of What are the details of using Java code blocks?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.