首页 技术 正文
技术 2022年11月19日
0 收藏 432 点赞 2,792 浏览 1437 个字

先初始化主类中的静态数据,如果要用其他类来定义对象,则初始化对应的其他类。

实例化对象时,先初始化定义为static的数据,接着调用父类的构造函数(如果有父类),再初始化定义为非static的数据,最后调用该类的构造函数。见http://www.cnblogs.com/HITSZ/p/6385271.html

通过一个小程序,了解静态数据是如何初始化的:

//: initialization/StaticInitialization.java
// Specifying initial values in a class definition.
import static net.mindview.util.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();
} /*
* Output:
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)
*/// :~

初始化顺序:要执行main,必须先加载StaticInitialization类,然后其静态域table和cupboard被初始化,这将导致它俩对应的类(Table,Cupboard)也被加载;

Table类和Cupboard类含有Bowl类的静态对象,这会导致Bowl类被加载;

这样,在这个特殊的程序中,所有类在main()开始之前就都被加载了。但实际情况通常并非如此,因为在典型的程序中,不会像在本例中所做的那样,将所有的事物都通过static联系起来。

构造函数没有使用static关键字,是隐式声明为static的。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,000
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,512
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,358
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,141
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,771
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,849