码迷,mamicode.com
首页 > 编程语言 > 详细

Java(多态练习 instanceof)

时间:2015-07-09 12:54:19      阅读:434      评论:0      收藏:0      [点我收藏+]

标签:

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

  

Java(多态练习 instanceof)

标签:

原文地址:http://www.cnblogs.com/IamJiangXiaoKun/p/4632722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!