java中的static关键字

来源:互联网 发布:steam淘宝哪些是黑礼物 编辑:程序博客网 时间:2024/06/05 08:05

按照是否静态的对类成员变量进行分类可分两种:一种是被static修饰的变量,叫静态变量或类变量;另一种是没有被static修饰的变量,叫实例变量。

static关键字的主要两个作用:

1. 为特定的数据类型或对象分配单一的存储空间,而与创建对象的个数无关。

2. 实现某个方法或属性与类而不是与对象关联在一起。


Java中提供了static方法和非static方法。static方法是类的方法,不需要创建对象就可以被调用,而非static方法是对象的方法,只有对象呗创建出来后才可以被使用。

static方法中不能使用this和super关键字,不能调用非static方法,只能访问所属类的静态成员变量和成员方法。

举个栗子~

像一些类只提供工具方法,而没有特殊数据的。

我们可以将其改为静态,从而直接调用。比如:

修改前:

public class ArrayToolDemo {    public static void main(String[] args) {  int[] arr = {3,8,5,6};  ArrayTool tool = new ArrayTool();  int max = tool.getMax(arr);  System.out.println("max="+max);  int index = tool.getIndex(arr, 10);  System.out.println("index="+index);   }}

public class ArrayTool {/* * 获取整型数组的最大值。 */    public int getMax(int[] arr){      int maxIndex=0;      for (int x = 0; x < arr.length; x++) {      if(arr[x]>arr[maxIndex]){      maxIndex = x;    }}     return arr[maxIndex];    }    public int getIndex(int[] arr,int key){    for (int x = 0; x < arr.length; x++) {if(arr[x] == key){return x;}}return -1;    }

修改后:

public class ArrayToolDemo {    public static void main(String[] args) {  int[] arr = {3,8,5,6};  int max = ArrayTool.getMax(arr);  System.out.println("max="+max);  int index = ArrayTool.getIndex(arr, 10);  System.out.println("index="+index);   }}

public class ArrayTool {/* * 获取整型数组的最大值。 */    public static int getMax(int[] arr){      int maxIndex=0;      for (int x = 0; x < arr.length; x++) {      if(arr[x]>arr[maxIndex]){      maxIndex = x;    }}     return arr[maxIndex];    }    public static int getIndex(int[] arr,int key){    for (int x = 0; x < arr.length; x++) {if(arr[x] == key){return x;}}return -1;    }