- public class Main {
- public static void main(String[] args) {
- /*使用Holder1*/
- Holder1 holder1 =newHolder1(newAutomobile("Iphone"));
- System.out.println(holder1.get().getName());
- /*使用Holder2*/
- //使holder2持有String类型对象Holder2 holder2 =newHolder2("XiaoMi");
- System.out.println(holder2.getObject());
- //更改holder2中持有的对象类型holder2.setObject(newAutomobile("HuaWei"));
- //向下转型Object->AutomobileAutomobile automobile = (Automobile) holder2.getObject();
- System.out.println(automobile.getName());
- /*使用Holder3*/
- //告诉编译器holder3持有的对象类型为String
- //此时holder3拥有的对象类型只能为String,不能变更Holder3 holder3 = newHolder3("Vivo");
- System.out.println(holder3.getT());
- //告诉编译器anotherHolder3持有的对象类型为Automobile
- //此时anotherHolder3拥有的对象类型只能为Automobile,不能变更Holder3 anotherHolder3 =newHolder3(newAutomobile("Oneplus"));
- System.out.println(anotherHolder3.getT().getName());
- }
- }
来源: