class Test
{
Test()
{
System.out.println("This is the default call class");
}
Test(int x)
{
System.out.println("This is the static call class test" + x);
}
}
class Vary
{
Vary()
{
System.out.println("This is the Vary's construct function");
}
int i;
short sh;
long lo;
float j;
double db;
byte by;
char ch;
boolean bo;
int ii = 1;
short ssh = 2;
long llo = 3;
float jj = 4;
double ddb = 5;
byte bby = 6;
char cch = '7';
boolean bbo = true;
Test test1;
Test test2 = new Test();
void printDefault()
{
System.out.println("This is the Default print");
System.out.println(i); //0 int
System.out.println(sh); //0 short
System.out.println(lo); //0 long
System.out.println(j); //0.0 float
System.out.println(db); //0.0 double
System.out.println(by); //0 byte
System.out.println(ch); //|_| (空白) char
System.out.println(bo); //false boolean
}
void printDefine()
{
System.out.println("This is the Define print");
System.out.println(ii); //1 int
System.out.println(ssh); //2 short
System.out.println(llo); //3 long
System.out.println(jj); //4.0 float
System.out.println(ddb); //5.0 double
System.out.println(bby); //6 byte
System.out.println(cch); //7 char
System.out.println(bbo); //true boolean
}
void printClass()
{
System.out.println("This is the Class print");
System.out.println(test1); //null
System.out.println(test2); //test@280bca
}
//*****************************************************************************************
void print()
{
System.out.println("what is wrong!");
}
int funInt(int xp)
{
return xp;
}
//如果只有”语句2“注释,那么语句1会报错:(xx2 cannot be resolved to a variable)
//如果语句1,2都不注释,那么语句1会报错:(Cannot reference a field before it is defined)
//说明不能用一个未定义或者说还没初始化的变量去初始化另外一个变量
// int xx1 = funInt(xx2); //语句1
// int xx2 = funInt(xx1); //语句2
//****************************************************************************************
//为了支持前向引用,java会先把所有的变量都加载到符号表中,符号表中的所有变量采用默认值,
//加载完后再按照变量的顺序进行初始化。因此xx3先初始化,它会调用函数funcReturn(),返回值
//是没有被初始化的n,结果就是0了。
int funReturn()
{
return xx4;
}
int xx3 = funReturn();// xx3 = 0,not 1
int xx4 = 1; // xx4 = 1
//***************************************************************************************
static Test test3 = new Test(3); //call this first
}
public class Varibles
{
public static void main(String[] args)
{
Vary varies = new Vary();
varies.printClass();
varies.printDefine();
varies.printDefault();
System.out.println("xx3 = " + varies.xx3);
System.out.println("xx4 = " + varies.xx4);
}
static Test test4 = new Test(4);
static Test test5 = new Test(5);
}
输出结果:
This is the static call class test4
This is the static call class test5
This is the static call class test3
This is the default call class
This is the Vary's construct function
This is the Class print
null
Test@39fc0f04
This is the Define print
1
2
3
4.0
5.0
6
7
true
This is the Default print
0
0
0
0.0
0.0
0
从上面可以看出:
2:static的变量初始化