import java.util.ArrayList;
import java.util.List;
/**
*
* @author ShunLi
*/
public class ExtendTest {
public static void main(String[] args) {
List<Person> pList = new ArrayList<Person>();
pList.add(new Person());
pList.add(new Person());
List<Animal> aList = new ArrayList<Animal>();
aList.add(new Animal());
doSomething(pList);
doSomething(aList);
}
static void doSomething(List<? extends Base> obj){
for (Base base : obj) {
base.doSomething();
}
}
}
interface Base{
void doSomething();
}
class Person implements Base{
public void doSomething() {
System.out.println("Person");
}
}
class Animal implements Base{
public void doSomething() {
System.out.println("Animal");
}
}
////////////////////////////////////////////////////////////////
import java.util.ArrayList;
import java.util.List;
/**
*
* @author ShunLi
*/
abstract class Base {
abstract void doSomething();
}
class Person extends Base {
public void doSomething() {
System.out.println("Person");
}
}
class Animal extends Base {
public void doSomething() {
System.out.println("Animal");
}
}
public class ExtendTest2 {
public static void main(String[] args) {
List<Person> pList = new ArrayList<Person>();
pList.add(new Person());
pList.add(new Person());
List<Animal> aList = new ArrayList<Animal>();
aList.add(new Animal());
doSomething(pList);
doSomething(aList);
}
static void doSomething(List<? extends Base> obj) {
for (Base base : obj) {
base.doSomething();
}
}
}
////////////////////////////////////////////////////////////////
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
*
* @author ShunLi
*/
abstract class Base {
abstract void doSomething();
}
class Person extends Base {
public void doSomething() {
System.out.println("Person");
}
}
class Animal extends Base {
public void doSomething() {
System.out.println("Animal");
}
}
public class ExtendTest3 {
public static void main(String[] args) {
List<Base> bases = new ArrayList<Base>();
bases.addAll(getPersons());
doSomething(bases);
bases.clear();
bases.addAll(getAnimals());
doSomething(bases);
doSomething(Arrays.<Base> asList(new Person(), new Animal()));
doSomething(Arrays.asList(new Person(), new Animal()));
bases.clear();
Collections.addAll(bases, new Person(), new Animal());
doSomething(bases);
}
private static List<Animal> getAnimals() {
List<Animal> aList = new ArrayList<Animal>();
aList.add(new Animal());
return aList;
}
private static List<Person> getPersons() {
List<Person> pList = new ArrayList<Person>();
pList.add(new Person());
pList.add(new Person());
return pList;
}
static void doSomething(List<Base> obj) {
for (Base base : obj) {
base.doSomething();
}
}
}
1. 抽象类抽象方法和接口差不多,而且个人以前没有理解过的是在 ExtendTest中,也可以使用List<implement> –> List<? extends Base>,接口还是可以理解成继承的;
2. ExtendTest3 中 Arrays.<Base> asList(new Person(), new Animal()) 这种写法还是从 《Thinking In Java》看到的,当然你可以忽略中间<Base>这样的书写;
3. 其它。
posted on 2011-10-28 23:41
李顺利 阅读(615)
评论(0) 编辑 收藏