创建Person父类
package com.oracle.demo02; public class Person { private String name; private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } public void work() { System.out.println("吃饭"); } }
创建Student子类
package com.oracle.demo02; import java.util.ArrayList; //泛型类 public class Student extends Person{public Student (String name,int age) { super(name,age); } public void work() { System.out.println("学习"); } }
创建Worker子类
package com.oracle.demo02; public class Worker extends Person{ public Worker(String name,int age) { super(name,age); } public void work() { System.out.println("工作"); } }
测试类
package com.oracle.demo02; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; public class Demo01 { public static void main(String[] args) { ArrayList<Student> arr=new ArrayList<Student>(); arr.add(new Student("小红", 18)); arr.add(new Student("小蓝", 18)); HashSet<Worker> brr=new HashSet<Worker>(); brr.add(new Worker("小红帽", 18)); brr.add(new Worker("小蓝帽", 18)); ArrayList<Person> crr=new ArrayList<Person>(); crr.add(new Person("小小", 18)); get(arr); get(brr); get(crr); } //通用的遍历集合的方法 public static void get(Collection<? extends Person> col) { // ? 泛型通配符 //泛型里没有多态,只能用限定符限定 // 泛型限定符 ? extends E(父类名称)--> 设置上限(最大父类) // 泛型限定符 ? super E(父类名称) --> 设置下限(最小父类) Iterator<?> it=col.iterator(); while (it.hasNext()) { Person p=(Person)it.next(); p.work(); break; } } }
.
原文地址:https://www.cnblogs.com/l1314/p/12108990.html
时间: 2024-10-29 11:39:34