有时候,类和方法需要对类型变量加以约束,比如你有一个方法,你只希望它接收某个特定类型及其子类型作为参数。
下面就举一个方法限定接收参数的类型的例子来说明如何限定类型变量。
首先有几个简单的辅助类:
package generic; public class Person extends Animal { private String name; public Person(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person [name=" + name + "]"; } }
package generic; public class Student extends Person { private String studentNumber; public Student(String name, String registrationNumber) { super(name); this.studentNumber = registrationNumber; } public String getStudentNumber() { return studentNumber; } public void setStudentNumber(String studentNumber) { this.studentNumber = studentNumber; } @Override public String toString() { return "Student [studentNumber=" + studentNumber + ", name=" + getName() + "]"; } }
package generic; public class Teacher extends Person { private String teacherNumber; public Teacher(String name, String teacherNumber) { super(name); // TODO Auto-generated constructor stub this.teacherNumber = teacherNumber; } public String getTeacherNumber() { return teacherNumber; } public void setTeacherNumber(String teacherNumber) { this.teacherNumber = teacherNumber; } @Override public String toString() { return "Teacher [teacherNumber=" + teacherNumber + ", name=" + getName() + "]"; } }
package generic; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Person person = new Person("li"); Student student = new Student("yuncong", "1"); Teacher teacher = new Teacher("wangfang", "99"); Building building = new Building("qiuyuan"); // test1 /** * test1说明getPersonInfo(T person)方法的参数只能是Person * 及其子类的实例; */ System.out.println(Test.getPersonInfo(person)); System.out.println(Test.getPersonInfo(student)); System.out.println(Test.getPersonInfo(teacher)); /** * Bound mismatch: The generic method getPersonInfo(T) of type Test is * not applicable for the arguments (Building). The inferred type * Building is not a valid substitute for the bounded parameter <T * extends Person> */ // System.out.println(Test.getPersonInfo(building));// error } / ** * T的限定类型决定了在方法中可以调用T的实例的哪些方法; * * @param person * @return */ public static <T extends Person> String getPersonInfo(T t) { return t.toString(); } }运行测试类的结果如下:
Person [name=li]
Student [studentNumber=1, name=yuncong]
Teacher [teacherNumber=99, name=wangfang]
类型变量的限定只有extends这一个关键字,extends可以接多个接口超类型,但是至多有一个类,如果extends后面跟有类,这个类必须是第一个。多个限定类型用&隔开。如:T extends Person & Comparable<T>。
原文地址:http://blog.csdn.net/l294265421/article/details/46413611