泛型应用于编译时还是运行时?
泛型是 Java 中的一个概念,在这里你可以启用一个类、接口和方法,将所有(引用)类型作为参数接受。换句话说,它是一个能让用户动态选择方法、类构造器所接受的引用类型。通过将一个类定义为泛型,你可以使其类型安全,即它能对任何数据类型起作用。
示例
class Student<T>{ T age; Student(T age){ this.age = age; } public void display() { System.out.println("Value of age: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student<Float> std1 = new Student<Float>(25.5f); std1.display(); Student<String> std2 = new Student<String>("25"); std2.display(); Student<Integer> std3 = new Student<Integer>(25); std3.display(); } }
输出
Value of age: 25.5 Value of age: 25 Value of age: 25
广告