static{代码} 叫做静态代码块 静态代码块最早执行,且只执行一次
{代码}叫做匿名代码块可以用来赋初始值 其次执行
静态方法可以直接从类中调用,而可以不用对象调用,而且推荐直接从类中调用
非静态方法可以调用静态变量和静态方法
但是静态方法里不能调用非静态变量及方法
原因 static都在一开始就加载,所以可以调。而非静态不是一开始就加载的,所以一开始根本就不存在,所以无法调用
package kuang.oop.Demo07;
public class Person {
{//其次执行
//代码块(匿名代码块) 可以赋初始值
System.out.println("匿名代码块");
}
static {//最早执行 只执行一次
//静态代码块
System.out.println("静态代码块");
}
public Person(){//最后执行 new一次就执行一次
System.out.println("构造方法");
}
public static void main(String[] args) {
Person p=new Person();
System.out.println("********");
Person p2=new Person();
}
}
package kuang.oop.Demo07;
//static
public class Student {
private static int age; //静态变量 多线程
private double score; //非静态变量
public void run(){ //非静态方法
}
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(); 非静态方法无法这么调用
go(); //静态方法可以这么调用
new Student().run(); //非静态方法需要实例调用
Student.go(); //可以直接调用
//原因 static都在一开始就加载,所以可以调 非静态不是一开始就加载的,所以一开始根本就不存在,所以无法调用
}