目录
static 理解为静态的,在 Java 中,static 关键字可以使用在变量、方法、代码块、内部类等,类被加载就初始化。static 关键字属于类,而不是实例。
static 修改变量称为静态变量。
示例
- public class Person {
-
- String name;
- int age;
- static String city = "深圳"; // 静态变量,属于类,所有对象共享。
-
- public Person(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
-
- public void talk() {
- System.out.println("我是:"+this.name + " 年龄:"+this.age+" 来自:"+city);
- }
-
- public static void main(String[] args) {
- Person p1 = new Person("张三",18);
- Person p2 = new Person("李四",19);
- Person p3 = new Person("王五",20);
- p1.talk();
- p2.talk();
- p3.talk();
- }
-
-
- }
假设程序产生了1000个Person对象,如果需要修改所有人 city 属性值,如果city属性值没有被static修饰,那是需要重新修改1000次 city 属性值,从开发以及内存管理来看,加了static话,像需要创建比较多实例对象并且对象有共同属性以及属性值也相同的情况下,可以用 static 修饰是可以适当提供内存效率的。
static 类型变量是所有对象共享的内存空间,也就是无论多少个对象产生,也只有一个 static 类型的属性。
示例内存图如下:

static 修改方法称为静态方法。静态方法无需创建对象就可以直接使用。
- public class Person {
-
- String name;
-
- static String city = "深圳";
-
- public void say(String name) {
- this.name = name;
-
- }
-
- public static void talk() {
- //say("张三");//静态方法不能调用非静态方法,编译不通过
- //this. 不能使用this关键字
- //super.不能使用super关键字
- System.out.println("我来自:"+city);
- }
-
- public static void main(String[] args) {
- talk(); //没有实例化对象,talk方法就可以直接使用
- }
-
-
- }
1、静态方法不能调用非静态的方法和变量。
2、不能使用this和super关键字。
static 修改代码块称为静态代码块。静态代码块,是 Java 类中的 static{ } 修饰的代码。用于类初始化时,为类的静态变量赋初始值,提升程序性能。
- public class Person {
-
- static { // 静态代码块
-
- }
-
- }
static 修改内部类称为静态内部类。
在创建静态内部类的实例时,不需要创建外部类的实例。
- public class Outer {
- static class Inner {
- }
- }
- class OtherClass {
- Outer.Inner inner = new Outer.Inner();//在创建静态内部类的实例时,不需要创建外部类的实例
- }
示例
- class Bowl{
- Bowl(int marker){
- System.out.println("Bowl("+marker+")");
- }
-
- void f1(int marker) {
- System.out.println("f1("+marker+")");
- }
- }
-
- class Tbable{
- static Bowl bowl= new Bowl(1);
- Tbable(){
- System.out.println("Tbable()");
- }
-
- void f2(int marker) {
- System.out.println("f2("+marker+")");
- }
- static Bowl bowl2= new Bowl(2);
- }
-
- class Cupboard{
- Bowl bow3= new Bowl(3);
- static Bowl bow4= new Bowl(4);
- Cupboard(){
- System.out.println("Cupboard()");
- bow4.f1(2);
- }
-
- void f3(int marker) {
- System.out.println("f3("+marker+")");
- }
- static Bowl bowl5= new Bowl(5);
- }
-
-
- public class StaticInitalization {
- public static void main(String[] args) {
- System.out.println("create new Cupboard() in main");
- new Cupboard();
- System.out.println("create new Cupboard() in main");
- new Cupboard();
- tbable.f2(1);
- cupboard.f3(1);
- }
- static Tbable tbable = new Tbable();
- static Cupboard cupboard = new Cupboard();
-
- }
控制台输出
- Bowl(1)
- Bowl(2)
- Tbable()
- Bowl(4)
- Bowl(5)
- Bowl(3)
- Cupboard()
- f1(2)
- create new Cupboard() in main
- Bowl(3)
- Cupboard()
- f1(2)
- create new Cupboard() in main
- Bowl(3)
- Cupboard()
- f1(2)
- f2(1)
- f3(1)
由示例可知:初始化对象是先静态对象。