java 基础 系列(二)

1.对于java语言,理解其代码执行顺序对于自己的程序性能等都是非常必要的,下面就切入正题介绍其执行顺序:

 

①:父类静态代码块->子类静态代码块(只执行一次);

②:父类成员变量的初始化或普通代码块->父类构造函数;

③:子类成员变量的初始化或普通代码块->子类构造函数。

 

示例代码:

 

package demo;

class Father {

//父类静态变量声明

private static int x=5;

protected static int y = 6;

//父类静态代码块

static{

System.out.println("y="+y);

System.out.println("x="+x);

System.out.println("class of Father..");

}

//父类普通代码块

{

System.out.println("To be or not to be..");

}

//父类构造器

public Father(){

int a=10;

int b=15;

System.out.println("a="+a+";b="+b+";str="+str);

}

//父类成员变量声明初始化

public String str="yeah";

}

public class Son extends Father{

//子类静态变量声明

public static String s="hello!";

//子类静态代码块

static{

System.out.println("s="+s);

System.out.println("class of Son..");

}

public static void main(String[] args) {

Son son = new Son();

son.introduce();

System.out.println("%%%%:"+Son.y);

System.out.println("====================================");

Son son2 = new Son();

}

//子类方法

public void introduce(){

System.out.println("how are you?");

}

}

 

 

打印信息:

 

y=6

x=5

class of Father..

s=hello!

class of Son..

To be or not to be..

a=10;b=15;str=yeah

how are you?

%%%%:6

====================================

To be or not to be..

a=10;b=15;str=yeah

 

 

猜你喜欢

转载自carrotgrandpa.iteye.com/blog/2249103