多態
父類的引用指向了自己的子類對象
父類的引用也可以接收自己的子類對象
必須是類與類之間有關系
通常還有一個前提
好處
弊端
代碼演示
動物
[java]
abstract class Animal
{
public abstract void eat()
}
class Cat extends Animal
{
public void eat()
{
System
}
public void catchMoust()
{
System
}
}
class Dog extends Animal
{
public void eat()
{
System
}
public void lookHome()
{
System
}
}
class Pig extends Animal
{
public void eat()
{
System
}
public void gongDi()
{
System
}
}
class DuoTaiDemo
{
public static void main(String[] args)
{
/*
Cat c
Cat c
Pig p = new Pig()
function(c
function(new Dog())
function(p)
*/
//Animal c = new Cat()
//c
//function(new Cat())
//function(new Dog())
//function(new Pig())
Animal a = new Cat()
a
//如果想要調用貓的特有方法時
//強制將父類的引用
Cat c = (Cat)a;
c
//千萬不要出現這樣的操作
//我們能轉換的是父類引用指向了自己的子類對象時
//多態自始至終都是子類對象在這這變化
//Animal a = new Animal()
//Cat c = (Cat)a;
}
public static void function(Animal a)
{
a
if(a instanceof Cat)
{
Cat c = (Cat)a;
c
}else if(a instanceof Dog)
{
Dog d = (Dog)a;
d
}
}
/*
public static void function(Cat c)
{
c
}
public static void function(Dog d)
{
d
}
public static void function(Pig p)
{
p
}
*/
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26595.html