多继承其实是不好的东西,但是你有时候却要用到它,那怎么办呢?可以利用接口,下面是一个简单的例子。
interface CanFly
{
void fly();
}
interface CanSwim
{
void swim();
}
interface CanFight
{
void fight();
}
class ActionCharter
{
public void fight()
{
System.out.println("I can fight");
}
}
class Hero extends ActionCharter implements CanFly,CanSwim,CanFight
{
public void swim(){
System.out.println("I can swim");
}
public void fly(){
System.out.println("I can fly");
}
}
public class HelloWorld
{
public static void u(CanFly i){i.fly();}
public static void v(CanSwim i){i.swim();}
public static void w(CanFight i){i.fight();}
public static void x(ActionCharter i){i.fight();}
public static void main(String []args)
{
Hero hero = new Hero();
u(hero);
v(hero);
w(hero);
x(hero);
}
}
讲解一下,这个例子里面在Hero继承了一个类ActionCharter来实现接口CanFight的功能,另外两个接口用方法实现,而在运行的时候采用动态绑定,来进行多态的实现,这个例子很简单,但是用在实际上却很有用