创建学生类
public class Student {
//创建学生类的私有属性
private String name;
private int age;
private double score;
//学生类的无参构造器
public Student() {
}
//学生类的有参构造器
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
//给私有的属性创建set get方法方便外界可以通过 学生对象. 的方式对学生类的属性进行赋值取值的操作
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 double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
//重新类Student类的toString方法
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
创建测试类:
public class Test {
public static void main(String[] args) {
//通过构造方法实例化学生对象
Student student1=new Student("sy",18,59.8);
Student student2=new Student("zs",20,59.0);
Student student3=new Student("lisi",18,59.0);
Student student4=new Student("wangwu",18,59.0);
Student student5=new Student("sunliu",22,100.0);
//实例化一共list对象
List list =new ArrayList();
//将学生对象通过add方法添加到list集合中
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
list.add(student5);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString());
}
}
}
运行结果:
Student{name='sy', age=18, score=59.8}
Student{name='zs', age=20, score=59.0}
Student{name='lisi', age=18, score=59.0}
Student{name='wangwu', age=18, score=59.0}
Student{name='sunliu', age=22, score=100.0}