我目前正在学习Java,并且是Java的初学者。我对装入一个类的含义感到非常困惑,尤其是如果该类中有一个名为Locations的静态块。这是我在课程中遇到的源代码的一部分。
public class Locations implements Map<Integer, Location> {
private static Map<Integer,Location> locations = new HashMap<>();
public static void main(String[] args) {
FileWriter file = null;
try{
file= new FileWriter("locations.txt");
for(Location location : locations.values()){
file.write(location.getLocationID()+ ", " +location.getDescription() + "\n");
}
} catch(IOException e){
System.out.println("In catch block");
e.printStackTrace();
} finally{
try{
if(file!=null){
System.out.println("Attempting to close file");
file.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
static{
locations.put(0, new Location(0, "You are sitting in front of a computer learning Java",null));
}
您应该阅读有关Java中类初始化序列的信息。对于一个类,它是静态块,静态变量,实例块,实例变量,然后构造函数被加载到内存中。如果班级有任何父母,那它会受到青睐。只需创建示例类并观察即可。
类加载器负责在运行时将Java类动态加载到JVM(Java虚拟机)。
Java类不会一次全部加载到内存中,而是在应用程序需要时加载。用于将类加载到内存中的类加载器。
注意:Oracle links提供的不错的教程>