static
-
在类中,用static声明的成员变量为静态成员变量,也成为类变量。类变量的生命周期和类相同,在整个应用程序执行期间都有效。
-
static修饰的成员变量和方法,从属于类
-
普通变量和方法从属于对象
-
静态方法不能调用非静态成员,编译会报错
-
static关键字的用途:方便在没有创建对象的情况下进行调用(方法/变量)。
-
被static关键字修饰的方法或者变量不需要依赖于对象来进行访问,只要类被加载了,就可以通过类名去进行访问。
-
static可以用来修饰类的成员方法、类的成员变量,另外也可以编写static代码块来优化程序性能
-
static方法也成为静态方法,由于静态方法不依赖于任何对象就可以直接访问,因此对于静态方法来说,是没有this的,因为不依附于任何对象,既然都没有对象,就谈不上this了,并且由于此特性,在静态方法中不能访问类的非静态成员变量和非静态方法,因为非静态成员变量和非静态方法都必须依赖于具体的对象才能被调用
package com.oop.demo07;
//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(s1.age);
System.out.println(s1.score);
go();
}
}
package com.oop.demo07;
public class Person {
//2:赋初始值
{
//代码块(匿名代码块)
System.out.println("匿名代码块");
}
//1:只执行一次
static{
//静态代码块
System.out.println("静态代码块");
}
//3
public Person(){
System.out.println("构造方法");
}
public static void main(String[] args) {
Person p = new Person();
System.out.println("==================");
Person p1 = new Person();
}
}
package com.oop.demo07;
//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;
public class Test {
public static void main(String[] args) {
System.out.println(random());
System.out.println(PI);
}
}