知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

    • Java OOP

    • 应知

      • Theory:Functional decomposition
      • Theory:Paradigms
      • Theory:Overloading
      • Theory:Write, compile, and run
      • Theory:Annotations basics
      • Theory:JVM, JRE, and JDK
      • Theory:Jave Archive
      • Theory:Running programs on your computer
      • Theory:Enums in Java
      • Theory:Fields and methods in enum
      • Theory:StringBuilder
      • Theory:Immutability
      • Theory:Boxing and unboxing
      • Theory:Introduction to generic programming
      • Theory:Generics and Object
      • Theory:What are collections
      • Theory:The collections Framework overview
      • Theory:ArrayList
      • Theory:The List interface
      • Theory:Comparable
      • Theory:Processing strings
      • Theory:Initialization blocks
        • Static initialization block
        • Instance initialization block
      • Theory:Introduction to API
      • Theory:Generic methods
    • 扩展

    • IO & Stream

    • Error & Exception

    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • 应知
Jim
2022-10-09
目录

Theory:Initialization blocks

# Static initialization block

A static initialization block is a block of code enclosed in braces {} and preceded by the static keyword:

static {
    // code
}
1
2
3

It's used to initialize static fields and constants, just like constructors help to initialize instance fields. We can create objects and invoke static methods in a static block.

Here is an example.

import java.util.Date;

public class StaticInitBlockExample {

    private static String stringField;
    private static Date dateField;

    private static final String A_STRING_CONSTANT;

    static {
        stringField = getEmptyString();
        dateField = new Date();
        A_STRING_CONSTANT = "unknown";
    }

    private static String getEmptyString() {
        return "empty";
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

A class can have multiple static blocks which will be executed in the order in which they appear in the source code. The values initialized in the first block are overwritten by the following blocks.

But the question is, what is performed earlier — the direct assignment to static fields or the static block?

See the following example.

public class StaticInitOrderExample {

    static int field = 30; // the first assignment

    static {
        field = 50; // the second assignment
    }
}
1
2
3
4
5
6
7
8

First, the direct assignment to the static field is performed. After that, the static block is executed. If you print the value of field, it will be equal to 50.

Note, it's impossible to access instance fields and methods in a static block.

A static initialization block is executed once for the whole class, not for each instance of the class.

# Instance initialization block

There is also an instance initialization block. It's used to initialize instance data members. It is run each time an object of the class is created. An instance initialization block is code enclosed in braces {}.

class InstanceInitBlockExample {

    private int field;

    {
        field = 40;
    }
}
1
2
3
4
5
6
7
8

Of course, we can also directly assign values to fields:

private int field = 40;
1

But if we need to perform more complex logic before a constructor is invoked, it's convenient to write an instance initialization block. For example, an instance initialization block is useful when we need to fill an array:

class ArrayInitExample {

    private int[] array;

    { 
        System.out.println("Before the constructor");

        array = new int[10];
        for (int i = 0; i < array.length; i++) {
            array[i] = i * i;
        } 
    }
    
    public void print() {
        for (int num : array) {
            System.out.printf("%d ", num);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

The instance initialization block is executed before any constructor of a class (but after the superclass constructors). The java compiler invokes the block as the first statement in the constructor, before other statements.

All instances of this class will be initialized during creation. There is an example:

public class UsingArrayExample {
    public static void main(String args[]) {
        ArrayInitExample obj = new ArrayInitExample();
        obj.print();
    }
}
1
2
3
4
5
6

This code outputs:

Before the constructor
0 1 4 9 16 25 36 49 64 81 
1
2

You can write as many initialization blocks as you need. They will be performed in the order in which they appear in your code.

提示

Note, static class members can be accessed in an instance initialization block.

编辑 (opens new window)
#Java
上次更新: 2022/12/03, 17:31:39
Theory:Processing strings
Theory:Introduction to API

← Theory:Processing strings Theory:Introduction to API→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式