java小白的学习记录......
1. 对象作为数组的步骤:
1)定义1个类。e.g. Teacher
2)其他类中定义一个方法接收对象参数
public void TeacherManage(Teacher tech){
......
}
2. 优点:避免参数过多造成代码麻烦,使得代码简洁
3. 实例
1)Teacher.java 代码,定义Teacher类
package cn.jbit.mydemos2;
public class Teacher {
public String name;
public int age;
public int id;
public double score;
public void show(){
System.out.println("name:"+name+"\nage:"+age
+"\nid:"+id+"\nscore:"+score+"\n");
}
}
2)TeacherManage.java 代码,定义Teacher数组
package cn.jbit.mydemos2;
public class TeacherManage {
//对象数组
Teacher[] teachers=new Teacher[10];
/**
* 对象参数的方法
* @param tc
*/
public void addTeacher(Teacher tc){
for(int i=0;i<teachers.length;++i){
if(teachers[i]==null){
teachers[i]=tc;
break;
}
}
}
public void showList(){
System.out.println("Print all the teachers' name:");
for(int i=0;i<teachers.length;++i){
if(teachers[i]!=null)
teachers[i].show();
}
}
}
3)测试代码,TestTeacher.java
package cn.jbit.mydemos;
import cn.jbit.mydemos2.Teacher;
import cn.jbit.mydemos2.TeacherManage;
public class TestTeacher {
public static void main(String[] args){
Teacher t1=new Teacher(); //Teacher对象1
t1.name="ZZ";
t1.id=1001;
t1.age=25;
t1.score=99;
Teacher t2=new Teacher(); //Teacher对象2
t2.name="Nana";
t2.id=1002;
t2.age=26;
t2.score=97;
TeacherManage ts=new TeacherManage();
//调用数组参数的方法
ts.addTeacher(t1);
ts.addTeacher(t2);
ts.showList();
}
}