这是Student类
package com.ma_0002;
/**
* 建立一个学生类,重写toString()方法
* @author TP
*
*/
public class Student {
/************成员变量区****************/
/**学生姓名*/
String name;
/**学生年龄*/
int age;
/************构造方法区****************/
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
/************get和set方法区****************/
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;
}
/************重写了toString()方法****************/
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
这是测试类StudentTest
package com.ma_0002;
/**
* Student测试类
* @author TP
*
*/
public class StudentTest {
/*
* 需求:
* 创建几个Student对角,并把它们放入一个数组中,然后输出
*
* 分析:
* 1.用Student构造方法创建对象
* 2.创建一个Student[]数组来放对象
* 3.输出
*/
public static void main(String[] args) {
//创建一个学生类对象
Student s = new Student("张大",1);
Student s2 = new Student("张二",2);
Student s3 = new Student("张三",3);
Student s4 = new Student("张四",4);
Student s5 = new Student("张五",5);
Student s6 = new Student("张六",6);
//创建一个Student[]数组来放对象
Student[] stuArr = new Student[6];
//给数组赋值
stuArr[0] = s;
stuArr[1] = s2;
stuArr[2] = s3;
stuArr[3] = s4;
stuArr[4] = s5;
stuArr[5] = s6;
//遍历输出数组元素
for (int i = 0; i < stuArr.length; i++) {
System.out.println("s"+i+" : "+stuArr[i]);
}
}
}
执行结果:
s0 : Student [name=张大, age=1]
s1 : Student [name=张二, age=2]
s2 : Student [name=张三, age=3]
s3 : Student [name=张四, age=4]
s4 : Student [name=张五, age=5]
s5 : Student [name=张六, age=6]