通过覆盖父类的方法来实现,在运行时根据传递的对象引用,来调用相应的方法
rihiroshitekiMacBook-Air:test LiBo$ java Integration
fish breathe
rihiroshitekiMacBook-Air:test LiBo$ cat Animal.java
class Animal
{
int height,weight;
Animal()
{}
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()
{}
void breathe()
{
// super.breathe();
System.out.println("fish breathe");
}
}
class Integration
{
static void fn(Animal an)
{
an.breathe();
}
public static void main(String[] args)
{
Animal an=new Animal();
Fish fh=new Fish();
an=fh;
Integration.fn(an);
// an.breathe();
// fh.height=30;
// fh.breathe();
}
}
子类没有这个方法,调用父类的方法:
rihiroshitekiMacBook-Air:test LiBo$ java Integration
animal breathe
rihiroshitekiMacBook-Air:test LiBo$ cat Animal.java
class Animal
{
int height,weight;
Animal()
{}
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()
{}
/* void breathe()
{
// super.breathe();
System.out.println("fish breathe");
} */
}
class Integration
{
static void fn(Animal an)
{
an.breathe();
}
public static void main(String[] args)
{
Animal an=new Animal();
Fish fh=new Fish();
an=fh;
Integration.fn(an);
// an.breathe();
// fh.height=30;
// fh.breathe();
}
}