34 lines
1.1 KiB
Java
34 lines
1.1 KiB
Java
package chapter6;
|
|
|
|
// T 标识一个不确定的类型
|
|
class Score<T> {
|
|
private String studentName; // 学生姓名
|
|
private String subject; // 课程名称
|
|
private T value; // 成绩值(可以是任意类型)
|
|
|
|
// 构造方法
|
|
public Score(String studentName, String subject, T value) {
|
|
this.studentName = studentName;
|
|
this.subject = subject;
|
|
this.value = value;
|
|
}
|
|
|
|
public String toString() {
|
|
return studentName + "的" + subject + "成绩是" + value;
|
|
}
|
|
}
|
|
|
|
public class Example22 {
|
|
public static void main(String[] args) {
|
|
// 创建三个成绩对象,分别存储小明的数学、英语、军事理论成绩
|
|
Score<Integer> s1 = new Score<Integer>("小明", "数学", 100);
|
|
Score<String> s2 = new Score<String>("小明", "英语", "A");
|
|
Score<String> s3 = new Score<String>("小明", "军事理论", "合格");
|
|
|
|
// 打印三门课程的成绩
|
|
System.out.println(s1);
|
|
System.out.println(s2);
|
|
System.out.println(s3);
|
|
}
|
|
}
|