通过覆盖父类的方法来实现,在运行时根据传递对象的引用,来调用相应的方法.
code:
class Animal
{
int height,weight;
Animal()
{
System.out.println("Animal construct");
}
void eat()
{
System.out.println("Animal eat!");
}
void sleep()
{
System.out.println("Animal sleep!");
}
void breathe()
{
System.out.println("Animal breathe!");
}
}
class Fish extends Animal
{
Fish()
{
System.out.println("Fish construct");
}
void breathe() //override method breathe()
{
System.out.println("Fish bubble");
}
}
class DoMain
{
static void fn(Animal an)
{
an.breathe();
}
public static void main(String[] args)
{
//Animal an=new Animal();
Fish fh=new Fish();
Animal an;
an=fh;
DoMain.fn(an);
}
}