首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

public 类的父类在同个文件,在加载的时分为何看起来还没访问就调用了父类的静态块,求拍砖

2013-12-11 
public 类的父类在同个文件,在加载的时候为何看起来还没访问就调用了父类的静态块,求拍砖package testpub

public 类的父类在同个文件,在加载的时候为何看起来还没访问就调用了父类的静态块,求拍砖

package test;



public class InitialzationSequence extends Super {
int i = 2;
static {
System.out.println("2.static block!");
}

Common common = new Common();
{
System.out.println("9.sub common block!");
}
public InitialzationSequence() {
System.out.println("10.sub constructor!");
}
public static void main(String[] args) {
System.out.println("4.normal action");
InitialzationSequence is = new InitialzationSequence();

}
static {
System.out.println("3.static block!");
}
}


class Super {
private int i = 1;
Common superCommon = new Common(1);

Super() {
System.out.println("7.super constructor!");
}

static {
System.out.println("1.super static block!");//why ?? load class ? 
}
{
System.out.println("6.super common block!");
}
}
class Common {
Common() {
System.out.println("8.sub common constructor!");
}
Common(int i) {
System.out.println("5.super common constructor!");
}
}


/*

outprint:


1.super static block!
2.static block!
3.static block!
4.normal action
5.super common constructor!
6.super common block!
7.super constructor!
8.sub common constructor!
9.sub common block!
10.sub constructor!

*/
[解决办法]
先调用父类的静态快,没错啊。不然你认为是怎样??
[解决办法]
引用:
Quote: 引用:

Quote: 引用:

类的静态块在加载该类时就会运行了,运行在构造函数的前面,并且先运行父类的


引用:
既然你InitialzationSequence类继承了Super类,要用InitialzationSequence类,必须先初始化父类撒。然后静态块又是优先初始化的。


引用:
继承了以后都会先调用父类的静态块


引用:
先调用父类的静态快,没错啊。不然你认为是怎样??

不好意思哈,描述不大清楚,问题不在1本身上,在1出现的位置上



static 和前后顺序没关系。




引用:
Quote: 引用:

类的静态块在加载该类时就会运行了,运行在构造函数的前面,并且先运行父类的


引用:
既然你InitialzationSequence类继承了Super类,要用InitialzationSequence类,必须先初始化父类撒。然后静态块又是优先初始化的。


引用:
继承了以后都会先调用父类的静态块


引用:
先调用父类的静态快,没错啊。不然你认为是怎样??

不好意思哈,描述不大清楚,问题不在1本身上,在1出现的位置上



初始化父类的话,执行顺序static块--非static块--构造块,所以会先执行父类的static块,然后再到子类的static块

热点排行