我有一个名为Teacher
的父类定义如下:
import java.util.LinkedList;
import java.util.List;
public class Teacher {
public List<Student> list = null;
public Teacher(String id) {
list = new LinkedList<Student>();
}
public void addStudent(Student tb){
list.add(tb);
}
}
和Student
:
public class Student {
public String getStudentName(){
return "student";
}
}
和扩展Teacher
的子类以及扩展Student
的子类:
import java.util.List;
public class MathStudent extends Student{
public String getStudentName(){
return "math student";
}
}
public class MathTeacher extends Teacher{
public MathTeacher(String id) {
super(id);
// TODO Auto-generated constructor stub
}
}
显然,MathTeacher
继承了方法addStudent
。
但问题是,当我构建一个MathTeacher
对象并为其添加一个学生时,我只想让它成为MathStudent
而不是Student
,如下所示:
MathTeacher clc = new MathTeacher("a");
MathStudent tc = new MathStudent();
clc.add(tc);
Student student = new Student();
clc.add(student); // I want this line to throw compling error to avoid a Student object is added
我该怎么办?我猜java泛型可能很有用。
答案 0 :(得分:2)
你可以实现它,例如:
public class Teacher <T extends Student> {
public List<T> list = null;
public Teacher(String id) {
list = new LinkedList<T>();
}
public void addStudent(T tb){
list.add(tb);
}
}
public class MathTeacher extends Teacher <MathStudent> {
public MathTeacher(String id) {
super(id);
// TODO Auto-generated constructor stub
}
}