1.static成员变量:属于整个类而不是某个实例对象,在类被加载时系统就会为其分配内存,直至程序结束退出才会被回收。
2.static方法:
静态方法中可以直接调用同类中的静态成员,不可以直接调用非静态成员,但是可以通过创建类的对象,然后通过对象来访问非静态成员;
静态方法中不可以直接调用非静态方法,但是可以通过对象来调用;
普通方法可以调用静态方法。
ps:静态方法是属于类的,内存必须为其分配空间,且一直被占用,当过多的声明静态方法容易使系统变慢,而普通的成员方法是由对象调用时才分配内存空间,当它没有被调用时会被回收空间。
3.下面看一个static修饰的变量和代码块与基类父类的执行顺序:
class Father{
public Father(){
System.out.println("Father construtor");
}
static{
System.out.println("Father static");
}
}
class Child extends Father{
public Child(){
System.out.println("Child construtor");
}
static{
System.out.println("Child static");
}
}
public class Hlist{
static{
System.out.println("Main static");
}
public static void main(String [] args){
new Child();
}
}
输出结果:
Main static
Father static
Child static
Father construtor
Child construtor
首先程序运行Hlist文件,static静态代码块在类加载时被初始化(static变量与方法只能初始化一次,如果已经初始化过,则不会再第二次初始化),首先输出Main static
程序找到main方法,需要new Child,由于Child继承自Father,因此需要先创建父类对象,在Father类中,有一个static代码块,子类Child中也有static代码块,优先输出Father static,接着输出Child static,然后执行父类构造函数,输出Father constructor,最后输出Child constructor。
总结:
static方法/变量与基类父类的执行顺序是:static变量/方法>main方法,基类初始化需要先加载父类的变量和方法。