1 package com.java.test; 2 3 import java.util.Random; 4 5 class Insect{ 6 //8.初始化基本类型变量i 7 private int i=9; 8 //(j没有初始化,不访问) 9 protected int j;10 public Insect() {11 //10.访问基类构造器12 System.out.println("i="+i+",j="+j);13 j=39;14 System.out.println("x1="+x1);15 }16 //9.初始化基本类型变量l17 private int l=10;18 //2.首先访问基类的static变量x1-调用静态方法19 private static int x1=printInit("static.x1 initialized.");20 static int printInit(String s){21 System.out.println(s);22 return new Random().nextInt(10)+1;23 }24 //3.依次初始化static块和static变量25 static {26 int z1=1;27 int z2=2;28 }29 static int y1=1;30 31 }32 33 public class JavaTest extends Insect{34 //11.初始化导出类基本变量k35 private int k=printInit("JavaTest.k initialized.");36 public JavaTest(){37 //13.访问导出类构造器38 System.out.println("k="+k);39 System.out.println("j="+j);40 System.out.println("x2="+x2);41 }42 //4.访问导出类的static变量x2-调用静态方法43 private static int x2=printInit("static.x2 initialized.");44 //5.依次初始化static变量和static块45 static int y2=2;46 static {47 int z3=1;48 int z4=1;49 }50 //12.初始化导出类基本变量p51 private int p=3;52 53 //1.寻找main入口,找出JavaTest类的编译代码(JavaTest.class文件中)54 public static void main(String[] args) {55 //6.进入main方法内部56 System.out.println("JavaTest constructor.");57 //7.初始化类58 JavaTest test= new JavaTest();59 //14.结束60 }61 }
输出:
static.x1 initialized.static.x2 initialized.JavaTest constructor.i=9,j=0x1=3JavaTest.k initialized.k=3j=39x2=6