static关键字详解
加了static的属性和方法
public class Student {
private static int age;//静态的变量
private double score;//非静态的变量
public void run(){
go();//非静态方法可以调用静态方法里的所有东西
}
public static void go(){
}
public static void main(String[] args) {
Student s1=new Student();
System.out.println(Student.age);//可以知道他是一个静态的变量
System.out.println(Student.score);
System.out.println(s1.age);
System.out.println(s1.score);
// run() 没办法调用,必须new一个run方法出来 ,如下:
new Student().run();
Student.go();//go j就不一样了
go();
}
}
代码图片:


=======================================================================================================
静态代码块:
public class Person {
{
System.out.println("匿名代码块");
}
static{
System.out.println("静态代码块");
}
public Person(){
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person =new Person();
}
}
输出结果:
静态代码块
匿名代码块
构造方法
//static 只执行一次,对象一创建就会先走匿名代码块,然后再走构造方法,如果有静态代码块,只会在第一次执行时先执行,且只执行一次
public class Person {
{
System.out.println("匿名代码块");
}
static{//static 只执行一次,对象一创建就会先走匿名代码块,然后再走构造方法
//如果有静态代码块,只会在第一次执行时先执行,且只执行一次
System.out.println("静态代码块");
}
public Person(){
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person1 =new Person();
System.out.println("================================");
Person person2=new Person();
}
}
输出结果:
静态代码块
匿名代码块
构造方法
匿名代码块
构造方法

浙公网安备 33010602011771号