1. 程式人生 > >Java泛型 泛型型別的繼承規則

Java泛型 泛型型別的繼承規則

泛型型別的繼承規則可能不能憑直覺的來想當然。下面舉個例子來看看泛型型別的繼承規則。

首先有幾個輔助類:

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;

import java.util.ArrayList;
import java.util.List;

public class Test2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// test1
		/**
		 * test1說明,雖然Student是Person的子類,但是
		 * ArrayList<Student>並不是ArrayList<Person>
		 * 的子類
		 */
		ArrayList<Student> students= new ArrayList<Student>();
		// error
		/**
		 * Type mismatch: cannot convert 
		 * from ArrayList<Student> to ArrayList<Person>
		 */
		ArrayList<Person> persons = students; // error
		
		// test2
		/**
		 * test2說明ArrayList<Person>是
		 * List<Student>的子類
		 */
		List<Student> students2 = students;

	}

}

test1和test2說明泛型型別只在類這個維度繼承,型別變數必須一樣,如ArrayList<E> implements List<E>。