多态(拆箱)继承封装实现将一组动物中的所有Dog对象,挑选出来,并保存在一个Dog类型的数组中,进行返回
在学习到第三周时,我学习到了面向对象的三大特性(封装、继承 和多态),今天用一个多态拆箱来实现将一组动物中的所有Dog对象,挑选出来,并保存在一个Dog类型的数组中,进行返回的案例。同时还可以通过 System.nanoTime() 获取程序运行的时间(单位:ns),定义一个父类Animal,两个子类Dog和Cat继承Animal父类。定义一个返回值为 Dog[] 数组参数为Animal[] 数组的方法 getAllDog(Animal[] animals)。通过instanceof 关键字判断Animal[]中的对象是否Dog对象,从而创建长度合适的Dog数组。然后用数组遍历实现Animal数组中为Dog对象的name,进而完成案例。
public class TestGetAllDog {
public static void main(String[] args) {
//long startMillis = System.currentTimeMillis();
Animal[] as = new Animal[6];
as[0] = new Dog("lucky");
as[1] = new Cat("xiaohua");
as[2] = new Dog("xiaohei");
as[3] = new Cat("xiaobai");
as[4] = new Dog("tom");
as[5] = new Cat("jerry");
//程序用时
long startNano = System.nanoTime();
Dog[] ds = getAllDog(as); // 30000 纳秒
System.out.println( System.nanoTime() - startNano );
for(int i = 0 ; i < ds.length ; i++) {
System.out.println( ds[i].getName() );
}
}
/**
* 将一组动物中的所有Dog对象,挑选出来,并保存在一个Dog类型的数组中,进行返回
* @param animals 一组动物对象
* @return Dog[] 一组Dog对象
*/
public static Dog[] getAllDog(Animal[] animals) {
//0.定义计数器
int count = 0;
//1.先数一遍,数组中有几只狗,然后再创建数组
for(int i = 0 ; i < animals.length ; i++) {
//1.1对数组中每个元素的类型,进行判断
if(animals[i] instanceof Dog) {
//1.2每发现一个Dog对象,计数器自增
count++;
}
}
//2.根据记数结果,创建长度合适的Dog数组
Dog[] dogs = new Dog[count]; // 0 1 2
//3.定于Dog的有效元素个数
int size = 0;
//4.将animals中的所有Dog对象,保存在Dog数组中
for(int i = 0 ; i < animals.length ; i++) { // 0 1 2 3 4 5
//4.1判断是否为Dog类型
if(animals[i] instanceof Dog) {
//4.2将Animal数组元素,进行强转后,保存在Dog数组中
dogs[size] = (Dog)animals[i];// Animal a0 = new Dog();
//4.3Dog数组的有效元素的计数器自增
size++;
}
}
//5.将保存了所有Dog对象的数组,返回给方法调用处
return dogs;
}
}
class Animal{
private String name;
public Animal() {
super();
}
public Animal(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
class Dog extends Animal{
public Dog() {
super();
}
public Dog(String name) {
super(name);
}
}
class Cat extends Animal{
public Cat() {
super();
}
public Cat(String name) {
super(name);
}
}
运行结果: