Java static关键字(重新认识main方法)
static 是静态的意思,可以修饰成员变量,也可以修饰成员方法
一、static修饰成员的特点
- 被其修饰的成员, 被该类的所有对象所共享
- 多了一种调用方式, 可以通过类名调用(推荐使用)
- 随着类的加载而加载, 优先于对象存在
//Student.java
public class Student {String name;int age;static String school;//使用static修饰
}
//Main.java
public class Main {public static void main(String[] args) {Student.school="xxxx大学";//通过类名调用,随着类的加载而加载, 优先于对象存在test1();//李四-----0----xxxx大学test2();//张三-----18----xx大学test1();//李四-----0----xx大学}private static void test1() {Student student=new Student();student.name="李四";System.out.println(student.name+"-----"+student.age+"----"+student.school);}private static void test2() {Student student=new Student();student.name="张三";student.age=18;student.school="xx大学";System.out.println(student.name+"-----"+student.age+"----"+student.school);}
}
test1()和test2()中,两个学生对象共享同一份school值
static修饰的成员变量,在内存中只有一份
二、static什么时候使用
- static 成员变量
- 共享数据(比如说一个网站的在线人数)
- static 成员方法
- 常用于制作工具类
工具类:不是描述事物的,而是帮我们完成一些事情
如果发现一个类所有方法,全是用static修饰
----私有该类的构造方法,目的:不让其他类再创建对象
例如:我们之前学的System类
案列:数组操作类
编写一个类 ArrayTools 内部编写三个方法
- 从数组中找最大值
- 从数组中找最小值
- 打印出数组中所有的元素, 要求格式为 [11, 22, 33]
public class ArrayTools {//私有该类的构造方法private ArrayTools(){}//从数组中找最大值public static int getMax(int[] arr){int max=arr[0];for (int i = 1; i < arr.length; i++) {if (arr[i]>max){max=arr[i];}}return max;}//从数组中找最小值public static int getMin(int[] arr){int min=arr[0];for (int i = 1; i < arr.length; i++) {if (arr[i]<min){min=arr[i];}}return min;}//打印出数组中所有的元素, 要求格式为 [11, 22, 33]public static void printArray(int[] arr){System.out.print("[");for (int i = 0; i < arr.length-1; i++) {System.out.print(arr[i]+",");}System.out.print(arr[arr.length-1]+"]");}
}
public class Test {public static void main(String[] args) {int[] arr={11,22,33};//直接使用类调用System.out.println(ArrayTools.getMax(arr));//33System.out.println(ArrayTools.getMin(arr));//11ArrayTools.printArray(arr);//[11,22,33]}
}
三、static注意事项
- static 方法中, 只能访问静态成员 (直接访问)
public class StaticDemo1 {static int num1=10;//静态成员变量int num2=20;//非静态成员变量//静态成员方法public static void method1(){System.out.println("static----method");}//非静态成员方法public void method2(){System.out.println("method");}public static void main(String[] args) {//可以直接访问System.out.println(num1);//10method1();//static----method//创建对象后才能访问非静态成员StaticDemo1 sd=new StaticDemo1();System.out.println(sd.num2);//20sd.method2();//method}
}
因为static修饰的成员随着类的加载而加载, 优先于对象存在,所以在对象还没创建之前便可以直接访问,但是非静态成员则不行。
- static 中不允许使用 this 关键字,因为this表示的是当前对象