测试类
import java.util.ArrayList;
public class Test {
public static void main(String [] args){
ArrayList<Student> List = new ArrayList<>();
//学生类中静态属性可以直接这样赋值,并且整个类的所有新建对象共用属性值
Student.teacher = "教主";
Student stu1 = new Student("张三",23,"男");
Student stu2 = new Student("李四",22,"男");
Student stu3 = new Student("王五",24,"男");
//赋值给集合
List.add(stu1);List.add(stu2);List.add(stu3);
//调用工具类
int max = StudentUtil.getMax(List);
System.out.println("学生中年龄最大为"+max);
StudentUtil.putText(stu1);
StudentUtil.putText(stu2);
StudentUtil.putText(stu3);
}
}
工具类
import java.util.ArrayList;
public class StudentUtil {
//私有化构造方法
//目的:不让外界创造对象 StudentUtil s = new StudentUtil();
private StudentUtil(){}
//静态方法
public static int getMax(ArrayList<Student> List){
//定义一个参照物
int max = List.get(0).getAge();
for(int i =1;i<List.size();i++){
int getage = List.get(i).getAge();
if(max<getage){
max = getage;
}
}
return max ;
}
public static void putText(Student stu){
System.out.println(stu.getName()+','+stu.getAge()+','+stu.getGender()+','+stu.getTeather());
}
}
学生类
public class Student {
private String name;
private int age;
private String gender;
//静态成员属性属于这个类公用的,每一个新建的成员方法中默认都有此属性值
static String teacher;
public Student(){
}
public Student(String name , int age , String gender){
this.name = name ;
this.age = age ;
this.gender = gender;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public static void setTeacher(String teacher) {
Student.teacher = teacher;
}
public static String getTeacher() {
return teacher;
}
}