一、目的
通过学生编号(Student_id ),找到对应 的班级
二、说明
需掌握知识:
抽象类
类部类
三、实例代码
1、ClassRoom.java
package abstract_test;
public abstract class ClassRoom {
// 根据学生id 找到 对应 班级
private String classRoom;
public ClassRoom(String classRoom ){
this.classRoom = classRoom;
}
public String getClassRoom() {
return classRoom;
}
public void setClassRoom(String classRoom) {
this.classRoom = classRoom;
}
abstract void findClass();
// 静态内部类
public static class Student{
private String ClassRoom_id; // 班级
public Student(String Student_id){ // 10207150486,
String ClassRoom_id = Student_id.substring(5, 7); // 取 15
this.ClassRoom_id = ClassRoom_id ;
}
public String getClassRoom_id() {
return ClassRoom_id;
}
public void setClassRoom_id(String classRoom_id) {
ClassRoom_id = classRoom_id;
}
}
}
2、Component.java
package abstract_test;
import java.util.ArrayList;
import java.util.List;
public class Component {
// 存放班级列表
public static List<ClassRoom> classRooms = new ArrayList<>();
// 三个班级
private static ClassRoom c1 = new ClassRoom("01"){
@Override
void findClass() {
System.out.println("这是1班学生");
}
};
private static ClassRoom c2 = new ClassRoom("02"){
@Override
void findClass() {
System.out.println("这是2班学生");
}
};
private static ClassRoom c15 = new ClassRoom("15"){
@Override
void findClass() {
System.out.println("这是15班学生");
}
};
// 将班级添加到 List<ClassRoom> 的方法
public static void addClassRoom(ClassRoom c){
classRooms.add(c);
}
// 启动后,自动加载 (重要知识)
static {
addClassRoom(c1);
addClassRoom(c2);
addClassRoom(c15);
}
// 根据 class_id 判别是 哪个班级学生
public static ClassRoom getClass(String class_id){
for(ClassRoom c : classRooms){
if(c.getClassRoom().equals(class_id)){
return c ;
}
}
return null ;
}
}
3、Test.java
package abstract_test;
import abstract_test.ClassRoom.Student;
public class Test {
public static void main(String[] args) {
Student s1 = new Student("10207150486");
String class_id = s1.getClassRoom_id();
ClassRoom c = Component.getClass(class_id);
c.findClass();
System.out.println("============");
Student s2 = new Student("10207010486");
c = Component.getClass(s2.getClassRoom_id());
c.findClass();
}
/*
输出结果:
这是15班学生
============
这是1班学生
*/
}