Java基础学习:面向对象14( static )
-
static关键字详解:
-
最先执行,静态代码块跟类一起加载;只执行1次;
-
-
-
代码案例1:
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(s1.age);
System.out.println(s1.score);*/
?
?
Student.go();
?
?
}
}
-
代码案例2:
?
public class Person {
?
/*{
//代码块(匿名代码块)
?
}
?
static {
?
//静态代码块
}*/
?
//2,用来:赋初始值
{
System.out.println("匿名代码块");
}
//1,最先执行,静态代码块跟类一起加载;只执行1次;
static {
System.out.println("静态代码块");
}
?
//3,
public Person() {
System.out.println("构造方法");
}
?
public static void main(String[] args) {
Person person1=new Person();
System.out.println("-------------------------");
Person person2=new Person();
?
/*
静态代码块
匿名代码块
构造方法
*/
?
}
}
?
?
?
-
扩展代码:静态导入包
//静态导入包
import static java.lang.Math.random;
?
public class Test {
?
public static void main(String[] args) {
//System.out.println(Math.random());//0.8410173058119216
System.out.println(random());//利用静态导入包
?
}
}