所呈现的程序说明了通用类的创建和使用。它定义了两个主要类:
创:
特点:
class gen<t> { t ob; // objeto do tipo t // construtor recebe um objeto do tipo t gen(t o) { ob = o; } // retorna o objeto t getob() { return ob; } // mostra o tipo do objeto armazenado void showtype() { system.out.println("type of t is " + ob.getclass().getname()); } }
gendemo:
class gendemo { public static void main(string args[]) { // gen com integer gen<integer> iob = new gen<>(88); iob.showtype(); // mostra o tipo: integer system.out.println("value: " + iob.getob()); // gen com string gen<string> strob = new gen<>("generics test"); strob.showtype(); // mostra o tipo: string system.out.println("value: " + strob.getob()); } }
程序输出:
Type of T is java.lang.Integer value: 88 Type of T is java.lang.String value: Generics Test
详细分析:
使用:
t 是一个类型参数,可以替换为任何实际类型(例如 integer 或 string)。
该参数在类声明中和使用 t 的方法中的 之间指定。
编译时类型检查:
gen 对象不能赋值给 gen,保证类型安全。
自动装箱:
java 自动将原始值(如 int)封装成相应的对象(integer),如 gen(88) 的情况。
方法showtype:
通过在封装对象上调用 getclass().getname() 显示实际存储的类型。
t 替换:
使用 gen 时,所有对 t 的引用都将替换为 integer。对于 gen,同样的情况也发生在 string 上。
删除:
在内部,编译器删除通用信息,将其替换为必要的强制,确保 gen 类的单一版本用于不同类型。
泛型的好处:
以上就是简单的通用示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号