public class StaticDemo1 {
public static void main(String[] args) {
Student.school = "传智专修学院"; //优先于对象的存在
Student stu1 = new Student();
stu1.name = "张三";
stu1.age = 23;
System.out.println(stu1.name + "---" + stu1.age + "---" +Student.school); //直接通过类名调用
System.out.println("---------------------");
Student stu2 = new Student();
stu2.name = "李四";
stu2.age = 23;
System.out.println(stu2.name + "---" + stu2.age + "---" +Student.school);
}
}
class Student {
String name;
int age;
static String school;
}
static对成员方法的修饰
常用于制作工具类
工具类:不是描述事物的,而是帮我们完成一些事情。
如果发现一个类中,所有的方法,全都是static所修饰
私有该类的构造方法
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;
}
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.println(arr[arr.length - 1] + "]");
}
}
目的: 为了不让其他类, 再创建对象
public class StaticDemo2 {
static int num1 = 10;
int num2 = 20;
public static void method(){
System.out.println("static...method");
}
public void print(){
System.out.println("print...");
}
public static void main(String[] args) {
// 在静态方法中, 只能访问静态成员(直接访问)
System.out.println(num1);
method();
StaticDemo2 sd = new StaticDemo2();
System.out.println(sd.num2);
sd.print();
}
}