对象初始化过程

aduan668 2008-04-23 12:24:00
哪位大侠分析下对象初化过程。有继承关系时和单个类时初始化有哪些区别呢?
能分别详细分析更好,先谢了
...全文
110 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
M_song 2008-04-30
  • 打赏
  • 举报
回复
自己总结的:
先是static变量和方法(类初始化),由clinit来初始化;
然后是实例变量,实例模块初始化,构造方法初始化,由init来初始化;
如果有继承关系,则先执行父类的初始化,然后才是子类的!
胡矣 2008-04-30
  • 打赏
  • 举报
回复


public class Father {
String fs = "Father's attribute";
{
System.out.println(fs);
}

static String fss = "Father's static attribute";
static{
System.out.println(fss);
}
Father(){
System.out.println("Father's constructor");
}

}
class Child extends Father{
String cs = "Child's attribute";
{
System.out.println(cs);
}

static String css = "Child's static attribute";
static{
System.out.println(css);
}
Child(){
System.out.println("Child's constructor");
}

}
class Test{
public static void main(String[] args) {
Child c = new Child();
}
}
/*
这里是运行结果:
Father's static attribute
Child's static attribute
Father's attribute
Father's constructor
Child's attribute
Child's constructor
*/

初始化顺序都是先父类,然后子类.
因为静态的属性是在类载入JVM时候进行的,所以:
1.父类静态属性/块.
2.子类静态属性/块.
然后开始初始化:
3.父类属性/块.
4.父类构造器.
5.子类属性/块.
6.子类构造器.
jiazhengjing 2008-04-23
  • 打赏
  • 举报
回复
LZ,可以看下这个帖
http://topic.csdn.net/u/20080402/21/6e9dc1dc-6ae5-4f41-a331-bbc74eb5b465.html
anqini 2008-04-23
  • 打赏
  • 举报
回复


package zhao;

public class Test2 extends AA {

static int age = 20;// 3

String code = "ANA";//8
static {
System.out.println("Test2 class static--------" + age);// 4
}
{
System.out.println("Test2 class not static--------" + code);//9
}

Test2() {
code = "DHC";
System.out.println("Test2()--------" + age);//10
}

public static void main(String[] args) {
try {
Class.forName("zhao.Test2");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
new Test2();
}
}

class AA {

static String tel = "123"; // 1

String name = "zhao";// 5
static {
System.out.println("AA class static--------" + tel);// 2
}
{
System.out.println("AA class not static--------" + name);//6
}

AA() {
name = "kimi";
System.out.println("AA()--------" + tel);//7
}
}
guoxyj 2008-04-23
  • 打赏
  • 举报
回复

1.父类静态属性
2.父类静态方法体
3.子类静态属性
4.子类静态方法体
5.父类非静态属性
6.父类非静态方法体
7.父类构造函数
8.子类非静态属性
9.子类非静态方法体
10.子类构造函数
panxuan 2008-04-23
  • 打赏
  • 举报
回复
重载与重写。
haoxiongok 2008-04-23
  • 打赏
  • 举报
回复
帮楼主顶上去

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧