Java(多態練習 instanceof)

來源:互聯網
上載者:User

標籤:

/* 題目: (多態,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;// 1public String getName(){return this.name;}public void setName(String name){this.name = name;}}class Dog extends Animal{// 2Dog(String name){this.getName();this.setName(name);}}class Cat extends Animal{// 3Cat(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){// 4Dog[] 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)     {  // 4List<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;}*/}}

  

Java(多態練習 instanceof)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.