Student); //true
// System.out.println(person instanceof Teacher); //不能编译
// System.out.println(person instanceof String); //不能编译
System.out.println("===================================");
Student student = new Student();
System.out.println(student instanceof Object); //true
System.out.println(student instanceof Student); //true
System.out.println(student instanceof Person); //true
// System.out.println(student instanceof Teacher); //不能编译
// System.out.println(student instanceof String); //不能编译
static
static修饰的属性和方法属于类本身,称为静态成员/方法,在类加载时一同加载,因此即使该类没有进行实例化,静态成员/方法也已经被分配了内存空间。而非静态成员和方法则只有在实例化时才被分配内存空间,这个生命周期的差异,使得在类仅加载还没有实例化的时候,非静态成员/方法对静态成员/方法是不可见的,为了避免出现非法访问内存的问题,静态成员/方法禁止访问非静态成员/方法。相反的,当非静态成员/方法加载时,静态成员/方法一定已经存在了,因此可以在非静态成员/方法中访问静态成员/方法,静态成员/方法也可以互相访问。
public class P4{
{
System.out.println("Anonymous code block!");
}
static {
System.out.println("Static anonymous code block!");
}
public P4(){
System.out.println("No parameter constructor!");
}
public static void main(String[] args){
P4 per1 = new P4();
System.out.println("==============");
P4 per2 = new P4();
}
}
执行结果如下:
可见静态代码块在类加载时首先执行,且在类生命周期中只被执行一次,而匿名代码块则在构造方法之前执行,且每次实例化都会执行。