1. 程式人生 > >java多型簡單例子 one

java多型簡單例子 one

/*
物件的多型性:動物 x = new 貓();
函式的多型性:函式過載、重寫

1、多型的體現
		父類的引用指向了自己的子類物件
		父類的引用也可以接收自己的物件
2、多型的前提
		必須是類與類之間只有關係,要麼繼承或實現
		通常還有一個前提,存在覆蓋
3、多型的好處
		多型的出現大大的提高了程式的擴充套件性
4、多型的弊端
		只能使用父類的引用訪問父類的成員
5、多型的應用

6、注意事項
*/

/*
需求:
貓,狗。
*/

abstract class Animal
{
	abstract void eat();
}

class Cat extends Animal
{
	public void eat()
	{
		System.out.println("吃魚");
	}
	public void catchMouse()
	{
		System.out.println("抓老鼠");
	}
}

class Dog extends Animal
{
	public void eat()
	{
		System.out.println("吃骨頭");
	}
	public void kanJia()
	{
		System.out.println("看家");
	}
}

class DuoTaiDemo
{
	public static void main(String[] args)
	{
		function(new Cat());
		function(new Dog());
		
		Animal a = new Cat();//向上轉型
		a.eat();
		
		Cat c = (Cat)a;//向下轉型
		c.catchMouse();
		
		
	}
	
	public static void function(Animal a)
	{
		a.eat();
		//用於子型別有限
		//或判斷所屬型別進而使用其特有方法
		if(a instanceof Cat)
		{
			Cat c = (Cat)a;
			c.catchMouse();
		}
		else if(a instanceof Dog)
		{
			Dog c = (Dog)a;
			c.kanJia();
		}
	}
	
	
}	
key:向上轉型、向下轉型、instanceof