Java 语言不厌其烦地试图保证变量在使用之前被合适地进行过初始化。
- 对于类中的变量,未被显式初始化的变量会被初始化为其默认值;
- 而对于方法中的变量,如果没有主动初始化,则编译器会以报错的方式保证变量初始化。
1.顺序初始化
在类内部,变量初始化的顺序是由其在类中的位置定义的。变量定义可能分散在类中各处,但是变量总是在任何方法被调用之前被初始化–甚至是构造函数。
package thinking.initialization;
import static fqy.iss.utils.Print.print;
public class OrderOfInitialization
{
public static void main(String[] args)
{
House h = new House();
h.f();
}
}
class Window
{
Window(int marker)
{
print("Window(" + marker + ")");
}
}
class House
{
Window w1 = new Window(1);
House()
{
print("House()");
w3 = new Window(33);
}
Window w2 = new Window(2);
void f()
{
print("f()");
}
Window w3 = new Window(3);
}
//result
Window(1)
Window(2)
Window(3)
House()
Window(33)
f()
2.有静态数据情形
package fqy.iss.thinking.initialization;
import static fqy.iss.utils.Print.print;
class Bowl
{
Bowl(int marker)
{
print("Bowl(" + marker + ")");
}
void f1(int marker)
{
print("f1(" + marker + ")");
}
}
class Table
{
static Bowl bowl1 = new Bowl(1);
Table()
{
print("Table()");
bowl2.f1(1);
}
void f2(int marker)
{
print("f2(" + marker + ")");
}
static Bowl bowl2 = new Bowl(2);
}
class Cupboard
{
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
Cupboard()
{
print("Cupboard()");
bowl4.f1(2);
}
void f3(int marker)
{
print("f3(" + marker + ")");
}
static Bowl bowl5 = new Bowl(5);
}
public class StaticInitialization
{
public static void main(String[] args)
{
print("Creating new Cupboard() in main");
new Cupboard();
print("Creating new Cupboard() in main");
new Cupboard();
table.f2(1);
cupboard.f3(1);
}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
}
//result
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)
- 静态数据仅仅被加载一次,只有一处副本存在;
- 类中数据初始化顺序是:静态数据按顺序初始化,然后是非静态数据顺序初始化,然后才执行构造函数。
2. 静态数据块初始化
package fqy.iss.thinking.initialization;
import static fqy.iss.utils.Print.print;
class Cup
{
Cup(int marker)
{
print("Cup(" + marker + ")");
}
void f(int marker)
{
print("f(" + marker + ")");
}
}
class Cups
{
static Cup cup1;
static Cup cup2;
static
{
cup1 = new Cup(1);
cup2 = new Cup(2);
}
Cups()
{
print("Cups()");
}
}
public class ExplicitStatic
{
public static void main(String[] args)
{
print("Inside main()");
Cups.cup1.f(99); // (1)
}
// static Cups cups1 = new Cups(); // (2)
// static Cups cups2 = new Cups(); // (2)
}
//result
Inside main()
Cup(1)
Cup(2)
f(99)