【百日精通JAVA | 语法篇】static关键字
一、static是什么?
static专门用于修饰成员变量和成员方法,被static修饰过的方法和变量我们称之为,静态变量和静态方法
二、static的内存图
代码如下:
注意:静态对象是随着类加载而加载的,优先于对象出现的。
三、练习
Test.java
import java.util.ArrayList;//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Test {public static void main(String[] args) {//创建一个集合存储学生对象ArrayList<Student> list = new ArrayList<>();Student stu1 = new Student("zhangsan",15,"男");Student stu2 = new Student("lisi",16,"男");Student stu3 = new Student("wangwu",17,"男");list.add(stu1);list.add(stu2);list.add(stu3);int max = StudentUtil.getMaxAgeStudent(list);System.out.println(max);}
}
StudentUtil.java
import java.util.ArrayList;public class StudentUtil {private StudentUtil(){};public static int getMaxAgeStudent(ArrayList<Student> list){int max = list.get(0).getAge();for (int i = 1; i < list.size(); i++) {if(max < list.get(i).getAge()){max = list.get(i).getAge();}}return max;}
}
Student.java
public class Student {private String name;private int age;private String gender;public Student() {}public Student(String name, int age, String gender) {this.name = name;this.age = age;this.gender = gender;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}}
三、static的注意事项
静态方法只能访问静态变量和静态方法。
非静态方法可以访问静态变量和静态方法,也可以访问非静态的成员变量和非静态的成员方法。
静态方法中没有this关键字。