/*
题目:
(多态,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;
}
*/
}
}

  

最新文章

  1. linux系统top命令查看系统状态
  2. mybatis There is no getter for property named &#39;xxxx
  3. Hive性能优化
  4. GDB深入研究
  5. swift中文文档翻译之--字符串和字符
  6. discuz怎么根据连接知道调用的是什么模板页面
  7. Bit Twiddling Hacks
  8. aliyun云服务器硬件性能测试
  9. EasyUI - ComboBox 下拉组件
  10. CentOS新增开机启动项
  11. SRILM的使用及平滑方法说明
  12. 【Spring】5、利用自定义注解在SpringMVC中实现自定义权限检查
  13. 从零开始搭建Salt Web之初探salt-api
  14. Docker中使用nginx镜像
  15. iframe解决ajax主域和子域之间的跨域问题
  16. C# 加特效
  17. fetch更新本地仓库两种方式:
  18. BZOJ.4909.[SDOI2017]龙与地下城(正态分布 中心极限定理 FFT Simpson积分)
  19. “秒杀”问题的数据库和SQL设计【转载】
  20. ZCTF2015 pwn试题分析

热门文章

  1. 苹果应用商店AppStore审核中文指南 分类: ios相关 app相关 2015-07-27 15:33 84人阅读 评论(0) 收藏
  2. MS SQL Server数据库修复/MDF数据文件数据恢复/MDF质疑/mdf无法附加
  3. 安卓 listview与arrayadapter
  4. mybatis sql中if判断传入Integer类型,传入0时,判断没有执行
  5. Sublime Text3 使用手册
  6. 笔记整理——linux程序设计
  7. codeforces 755D. PolandBall and Polygon
  8. 会话Cookie及session的关系(Cookie &amp; Session)
  9. GWAS
  10. 2.11. 创建托管对象(Core Data 应用程序实践指南)