static 关键字的作用


java中的static关键字主要用于内存管理。我们可以应用java static关键字在变量,方法,块和嵌套类中。 static关键字属于类,而不是类的实例。

static关键字可以修饰

变量

如果将一个变量声明为static,它就是所谓的静态变量了,静态变量可以用于引用所有对象的公共属性。它能使程序存储器高效(即它节省内存)。例如id计数。
eg1:公共属性

class Student {
    int id;
    String name;
    static String college = "xiangTanUnverisity";

    Student8(int r, String n) {
        rollno = r;
        name = n;
    }

    void display() {
        System.out.println(rollno + " " + name + " " + college);
    }

    public static void main(String args[]) {
        Student8 s1 = new Student8(111, "Karan");
        Student8 s2 = new Student8(222, "Aryan");

        s1.display();
        s2.display();
    }
}

输出结果

111 Karan ITS
222 Aryan ITS

id自增示例:
如果不是静态变量

class Counter {
    int id = 0;
    Counter() {
        id++;
        System.out.println(id);
    }

    public static void main(String args[]) {

        Counter c1 = new Counter();
        Counter c2 = new Counter();
        Counter c3 = new Counter();

    }
}

输出结果

1
1
1

如果是静态变量

class Counter2 {
    static int id = 0;

    Counter2() {
        id++;
        System.out.println(id);
    }

    public static void main(String args[]) {

        Counter2 c1 = new Counter2();
        Counter2 c2 = new Counter2();
        Counter2 c3 = new Counter2();

    }
}

输出结果

1
2
3

从而引出内存存储位置图:
在这里插入图片描述

方法

静态方法有一下特性

  • 静态方法属于类,而不属于类的对象。
  • 可以直接调用静态方法,而无需创建类的实例。
  • 静态方法可以访问静态数据成员,并可以更改静态数据成员的值。

静态方法的限制

  • 静态方法不能直接使用非静态数据成员或调用非静态方法。
  • 静态方法不能使用this和super。
class A {
    int a = 40;// non static

    public static void main(String args[]) {
        System.out.println(a);
    }
}

输出结果

[编译错误!]Compile Time Error

如果将a修饰为静态变量则输出结果为:
static int a = 40;

40

代码块

作用

  • 初始化静态数据成员
  • 在main方法之前就执行

eg:

class A2 {
    static {
        System.out.println("static block is invoked");
    }

    public static void main(String args[]) {
        System.out.println("Hello main");
    }
}

输出顺序为:

static block is invoked
Hello main

内部类

根据Oracle官方的说法:

Nested classes are divided into two categories: static and non-static.
Nested classes that are declared static are called static nestedclasses.
Non-static nested classes are called inner classes.

从字面上来说,一个是静态镶嵌内部类,一个是内部类。
此处直降static关键字,不深究,可以随时去官网查看:Nested Classes

猜你喜欢

转载自blog.csdn.net/weixin_43101144/article/details/84339835