Java范式1
Posted 韩凯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java范式1相关的知识,希望对你有一定的参考价值。
package Xwxx; public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
package Xwxx; public class Student extends Person{ private String name; private int age; public Student(){ } public Student(String name, int age) { this.name=name; this.age=age; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } }
package Xwxx; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class Test { public static void main(String[] args) { ArrayList<Person> list=new ArrayList<Person>(); list.add(new Person("zhangsan",28)); list.add(new Person("lisi",18)); printCollection(list); ArrayList<Student> l=new ArrayList<Student>(); l.add(new Student("小明",22)); l.add(new Student("小红",20)); printCollection(l); } public static void printCollection(Collection<?> list){ //变成了object类了,所以只能访问object的方法 //? extends Person是接收Person和其子类 //? super Student是接收Student和其父类 Iterator<?> it=list.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } }
以上是关于Java范式1的主要内容,如果未能解决你的问题,请参考以下文章