/* 题目: (多态,instanceof)有如下代码 class Animal { private String name; // 1 } class Dog extends Animal { //2 } class Cat extends Animal { //3 } public class TestAnimal { public static void main(String args[]){ Animal[] as = new Animal[]{ new Dog("Pluto"), new Cat("Tom"), new Dog("Snoopy"), new Cat("Garfield") }; Dog[] dogs = getAllDog(as); for(int i = 0; i<=dogs.length; i++) { System.out.println(dogs[i].getName()); } } public static Dog[] getAllDog(Animal[] as) { //4 } } 程序填空: a) 在 //1, //2, //3 处填上适当的get/set 方法和构造方法 b) 完成//4 处的填空。getAllDog 方法从一个Animal 数组中挑选出所有的Dog 对象,并把这些对象放在一个Dog 数组中返回。 */ package MyTest; class Animal { private String name; // 1 public String getName() { return this.name; } public void setName(String name) { this.name = name; } } class Dog extends Animal { // 2 Dog(String name) { this.getName(); this.setName(name); } } class Cat extends Animal { // 3 Cat(String name) { this.getName(); this.setName(name); } } public class TestAnimal { /* * @param args */ public static void main(String[] args) { Animal[] as = new Animal[] { new Dog("Pluto"), new Cat("Tom"), new Dog("Snoopy"), new Cat("Garfield") }; Dog[] dogs = getAllDog(as); for (int i = 0; i < dogs.length; i++) { System.out.println(dogs[i].getName()); } } public static Dog[] getAllDog(Animal[] as) { // 4 Dog[] dog = new Dog[as.length]; int len = as.length; int j = 0; for(int i = 0;i<len;i++) { if(as[i] instanceof Dog) { dog[j] = (Dog)as[i]; j++; } } ////////////////// Dog[] dg = new Dog[j]; for(int i = 0;i<j;i++) { dg[i] = dog[i]; } ////////////////// return dg; /* 方法二: public static Dog[] getAllDog(Animal[] as) { // 4 List<Dog>dd = new ArrayList<Dog>(); for(int i=0; i<as.length; i++) { //System.out.println(as[i].getClass().getName()); if (as[i].getClass().getName().contains("Dog"))//( as[i] instanceof Dog ) { dd.add((Dog)as[i]); } } int size = dd.size(); Dog[] cc = (Dog[])dd.toArray(new Dog[size]); return cc; } */ } }
时间: 2024-11-09 03:48:52