学生类
package StaticTest;public class Student {private String name;private int age;private static String teacher;public Student(){}public Student(String name, int age) {this.name = name;this.age = age;}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 static String getTeacher() {return teacher;}public static void setTeacher(String teacher) {Student.teacher = teacher;}// 静态方法只能访问静态方法和静态变量/*public static void show1() {System.out.println(name); // 报错:无法从static上下文引用非static字段"name"System.out.printf(teacher); // 用静态变量不报错getAge(); // 报错:无法从static上下文引用非static方法"getAge()"setTeacher("xl"); // 用静态方法不报错}*/public void show2() {System.out.println(name); // 用非静态变量不报错System.out.printf(teacher); // 用静态变量不报错int age = this.getAge(); // 用非静态方法不报错Student.setTeacher("xl"); // 用静态方法不报错}}
测试
package StaticTest;
import java.util.Scanner;
import java.util.ArrayList;
public class StaticTest {public static void main(String[] args) {Scanner sc = new Scanner(System.in);ArrayList<Student> studentsList = new ArrayList<Student>();System.out.println("请输入学生老师的名字");String name = sc.next();Student.setTeacher(name);System.out.println("要创建多少个学生?");int n = sc.nextInt();for (int i = 0; i < n; i++) {Student s = creatStudent();studentsList.add(s);}showStudent(studentsList);}public static Student creatStudent() {Scanner sc = new Scanner(System.in);System.out.println("请输入学生的名字");String name = sc.next();System.out.println("请输入学生的年龄");int age = sc.nextInt();return new Student(name, age);}public static void showStudent(ArrayList<Student> studentArrayList) {for (int i = 0; i < studentArrayList.size(); i++) {System.out.printf("学生%s的年龄是%d,老师是%s\n", studentArrayList.get(i).getName(),studentArrayList.get(i).getAge(), Student.getTeacher());}}
}