由下面的代码引入:
import java.util.Scanner;
class Animal{
public void show()
{
System.out.println("动物!");
}
}
class Student{
Animal a=new Animal();
private int age;
private String name;
static String country="美国";
static{
country="中国";
name="巨鲁布灵";
System.out.println("执行静态块");
}
{
System.out.println("执行非静态块");
}
public Student()
{
System.out.println("执行默认构造函数");
}
public Student(String name,int age)
{
System.out.println("执行构造函数");
this.name=name;
this.age=age;
this();
}
public static void show()
{
System.out.println("我叫"+name+",今年"+age+"岁,来自"+country);
}
}
public class awt_11 {
static Scanner input=new Scanner(System.in);
public static void main(String args[])
{
String Name=input.next();
int Age=input.nextInt();
Student s=new Student(Name,Age);
s.show();
}
对于上面的代码运行后有三个错误:
1>16行,static函数中无法访问"实例变量"与"实例函数"。所以在static初始模块无法对name进行初始化。
2>31行,这里的this()是访问不带参数的构造函数,所以应该放在函数体的第一行。
3>35行,static函数中无法访问实例变量。可以删除static修饰符。
修改后的代码为:
import java.util.Scanner;
class Animal{
public Animal()
{
System.out.println("动物!");
}
}
class Student{
Animal a=new Animal();
private int age;
private String name;
static String country="美国";
static{
country="中国";
System.out.println("执行静态块");
}
{
System.out.println("执行非静态块");
}
public Student()
{
System.out.println("执行默认构造函数");
}
public Student(String name,int age)
{
this();
System.out.println("执行构造函数");
this.name=name;
this.age=age;
}
public void show()
{
System.out.println("我叫"+name+",今年"+age+"岁,来自"+country);
}
}
public class awt_11 {
static Scanner input=new Scanner(System.in);
public static void main(String args[])
{
String Name=input.next();
int Age=input.nextInt();
Student s=new Student(Name,Age);
s.show();
}
}
执行输入:
许增强
20
后输出:
执行静态块
动物!
执行非静态块
执行默认构造函数
执行构造函数
我叫许增强,今年20岁,来自中国
运行过程:
jvm(java虚拟机)加载java.class文件(读取),首先对static成员变量进行初始化,执行静态代码块,然后对非static成员变量初始化,
执行非静态代码块,执行对构造函数进行初始化。
由于static变量在类加载时,对象创建之前就已经被初始化。
所以当执行:
Student s=new Student(Name,Age);
当需要用到类的时候,类就会被加载。执行static初始化模块,输出:执行静态块。
紧接着执行非静态块的初始化,先运行:
Animal a=new Animal();输出:动物!之后的输出就很明显了,不做解释。。