当前位置:网站首页>Understanding and learning of code blocks
Understanding and learning of code blocks
2022-07-27 01:37:00 【Daxiong who loves learning】
List of articles
Basic introduction
A code block belongs to a member of a class , It's similar to the method , Encapsulate logical statements in the method body , adopt {} Surrounded .
But different from the method , No method name , No return , No parameters , Only the method body , And you don't have to call... Explicitly through objects or classes , But when loading classes , Or implicitly call... When creating an object
Basic grammar
Modifier {
Code };
Note description :
1. Modifier can be written or not , What to write , I can only write static
2. If you use static Modifiers are called static code blocks , If there is no static The modification is called ordinary code block
3 A logical statement can be any logical statement ( Input and output , Method call , Cycle, etc )
4; The number can be written , You can omit it
The benefits of code blocks
1. Equivalent to another form of constructor ( Complementary mechanisms to constructors ), You can do initialization
2. scene : If there are repeated statements in multiple constructors , It can be extracted into the initialization block , Improve code reuse
Code case :
class Movie {
private String name;
private double price;
private String director;
//3 Constructor -> heavy load
{
System.out.println(" The movie screen opens ...");
System.out.println(" Advertising begins ...");
System.out.println(" The film is just the beginning ...");
};
public Movie(String name) {
System.out.println("Movie(String name) Called ...");
this.name = name;
}
public Movie(String name, double price) {
this.name = name;
this.price = price;
}
public Movie(String name, double price, String director) {
System.out.println("Movie(String name, double price, String director) Called ...");
this.name = name;
this.price = price;
this.director = director;
}
}
** explain :** The three constructors consist of the same statement , In order to avoid excessive redundancy of code , We use code blocks to initialize the constructor , Then we can put the same sentence , Put it into a code block , So when we call any constructor , Create objects , Will call the contents of the code block first , Last , Remember that the order of code block calls takes precedence over constructors .
Code block usage details
When is it implemented
static The function of the code block is to initialize the class , And it executes as the class loads , And only once . If it's a normal code block , Every time an object is created, it executes .
When the class is loaded **【 a key 】**
When creating an object instance (new When an object )
Create subclass object instances , The parent class is also loaded
Here is an explanation of why the parent class is also loaded , When we create subclass objects , Will contain a constructor , The default is parameterless constructor , There is an implicit super Point to the parent class , So if the parent class is also composed of static code blocks , Will load first
When using static members of a class ( Static attribute , Static methods )
eg:A class extends B class The static block of
Common code block , When creating an object instance , Will be called , To create a , Call once .
If you only use members of a class , Ordinary blocks of code do not execute
class BB {
{
System.out.println("BB Common code blocks 2 Be performed ...");
}
// Static code block
static {
System.out.println("BB Static code 1 Be performed ...");//1
}
}
class AA extends BB {
// Static code block
static {
System.out.println("AA Static code 1 Be performed ...");//2
}
{
System.out.println("AA Common code blocks 2 Be performed ...");
}
}
// Class is loaded, for example
// 1. When creating an object instance (new)
AA aa = new AA();
//2. Create subclass object instances , The parent class is also loaded , and , The parent class is loaded first , Subclasses are loaded
AA aa2 = new AA();

The execution order of the two code blocks
Here we first remember Static code blocks are executed before ordinary code blocks , The order of execution will be described in detail later
When creating an object , When a class is called in sequence ( No inheritance ):( a key )
- Call static code block and static attribute initialization ( Static code blocks have the same priority as static attribute initialization calls , Call according to their defined properties
- Call the initialization of common code blocks and common attributes ( The priority of ordinary code block and ordinary attribute initialization call together , Call in the order they define )
- Call constructor
class C02 {
private int n1 = 100;
private static int n2 = 200;
private static int n3 = 300;
public C02() {
System.out.print("C02 The constructor is called ...");
}
private void m1() {
System.out.println("m1 Method is called ...");
}
private static void m2() {
System.out.println("m2 Method is called ...");
}
static {
// Static code block , Only static members can be called
//System.out.println(n1); error
System.out.println(n2);//ok
//m1();// error
m2();
}
{
// Common code block , You can use any member
System.out.println(n1);
System.out.println(n2);//ok
m1();
m2();
}
}
new C02();

The execution order of the two code blocks in the class
When creating a subclass object , The calling order when calling a class :
- Static code blocks and static attributes of the parent class ( The priority is the same , In order of definition )
- Static code and static attributes of subclasses ( The priority is the same , In order of definition )
- Parent class common code and common attributes ( The priority is the same , In order of definition )
- Parent class constructor
- Common code blocks and common attributes of subclasses ( The priority is the same , In order of definition )
- Subclass construction method
class A02 {
// Parent class
private static int n1 = getVal01();
static {
System.out.println("A02 A static block of code ..");//(2)
}
{
System.out.println("A02 The first common block of code ..");//(5)
}
public int n3 = getVal02();// Initialization of common properties
public static int getVal01() {
System.out.println("getVal01");//(1)
return 10;
}
public int getVal02() {
System.out.println("getVal02");//(6)
return 10;
}
public A02() {
// Constructors
// hide
//super()
// Initialization of common code and common properties ......
System.out.println("A02 Constructor ");//(7)
}
}
class B02 extends A02 {
//
private static int n3 = getVal03();
static {
System.out.println("B02 A static block of code ..");//(4)
}
public int n5 = getVal04();
{
System.out.println("B02 The first common block of code ..");//(9)
}
public static int getVal03() {
System.out.println("getVal03");//(3)
return 10;
}
public int getVal04() {
System.out.println("getVal04");//(8)
return 10;
}
// Be sure to taste it slowly ..
public B02() {
// Constructors
// Hide the
//super()
// Initialization of common code blocks and common attributes ...
System.out.println("B02 Constructor ");//(10)
}
}
new B02();
Here is an explanation of why static code blocks are executed first , Because statically related code blocks , Property initialization , When the class loads , It's done , Therefore, it takes precedence over constructors and ordinary code blocks
Member permission requirements in code
Code blocks can only call static members directly , Ordinary code blocks can call any member
summary
I'm reviewing recently java Basic knowledge of , When learning the code block of Tao, I found that I was not familiar with it , So keep notes for future review .
边栏推荐
- 1100: finding the number of combinations (function topic)
- 13、 Command gadget
- [ctf attack and defense world] questions about cookies in the web area
- [by pass] bypass method of WAF
- OJ question of sequence table
- LAMP+DISCUZ论坛
- Producer consumer model of concurrent programming
- [Oracle] get the latest working day and the previous N working days
- Unity a user-friendly UI grayscale shader
- Introduction to mathematical modeling - from real objects to mathematical modeling [2]
猜你喜欢
![Introduction to mathematical modeling - from real objects to mathematical modeling [2]](/img/b5/595a4e9a9a59ab57f541d3e21fba49.jpg)
Introduction to mathematical modeling - from real objects to mathematical modeling [2]

七、循环语句

Web服务(04)——LAMP的简介与搭建+DISCUZ论坛
![[unity] unity interface scene view [1]](/img/5a/c34ff09ef1ddba4b65c7873775c251.png)
[unity] unity interface scene view [1]

The difference between if and else if

Jenkins -- Basic -- 5.1 -- system configuration -- plug-in management

Unity uses navmesh to realize simple rocker function

Vis workflow - plantcv

Web服务器(01)——介绍web服务器
![[SQL injection] extended injection method](/img/a1/d4218281bfc83a080970d8591cc6d4.png)
[SQL injection] extended injection method
随机推荐
系统安全及应用
LAMP+DISCUZ论坛
Download pronunciation pairs+ship or sheet+tree or three
hdc_ std
Deep learning notes
15、 Expect
11、 Echo
ESP8266-----JSON----c函数库提供字符串函数
Unity uses navmesh to realize simple rocker function
正则表达式之小工具系列
Naive Bayes multiclass training model
The difference between if and else if
Shell(9)函数
正则表达式
Unity screenshot widget
Finding the greatest common divisor
13、 Command gadget
1100: finding the number of combinations (function topic)
ESP8266 AP_ UDP_ Client
Basic introduction to Matlab [1]