package pkg;
//... interface ...
interface CanFight{// 1st
void fight();//just a claim
void jodo();
}
interface CanSwim{// 2nd
void swim();
void frogswim();
}
interface CanFly{// 3rd
void fly();
void butterfly();
}
//... class ...
class ActionCharacter{
public void fight() {// 1st
System.out.println("fight in ActionCharacter");
}
public void butterfly() {
System.out.println("butterfly in ActionCharacter");
}
}
//... sub class ...
class Hero extends ActionCharacter implements CanFight,CanSwim,CanFly{// .KEY.
//The type Hero must implement the inherited abstract method CanSwim.frogswim()
@Override
public void swim() {// 2nd
System.out.println("swim in hero");
}
@Override
public void fly() {// 3rd
System.out.println("fly in hero");
}
public void jodo() {//override
System.out.println("jodo in Hero");
}
@Override
public void butterfly() {
System.out.println("butterfly in Hero");
}
}
//... main ...
public class p179 {
public static void t(CanFight x) {x.fight();}
public static void j(CanFight x) {x.jodo();}
public static void u(CanSwim x) {x.swim();}
public static void f(CanSwim x) {x.frogswim();}
public static void v(CanFly x) {x.fly();}
public static void b(CanFly x) {x.butterfly();}
public static void w(ActionCharacter x) {x.fight();}
public static void main(String[] args) {
Hero hero=new Hero();
//UPcast hero to >>...
t(hero);/*fight in ActionCharacter
KEY:(get the method in BASE class when there are no definition in SUB class)*/
j(hero);//jodo in Hero ..(general INTERFACE invoke)
u(hero);//swim in hero
/*f(hero);// no definition in both of
* Exception in run,but can be compiled successfully
* */
v(hero);//fly in hero
b(hero);//butterfly in Hero (subclass method replaces baseclass method)
w(hero);//fight in ActionCharacter ..(general BASE METHOD invoke)
}
}
output:
fight in ActionCharacter
jodo in Hero
swim in hero
fly in hero
butterfly in Hero
fight in ActionCharacter
总结:
1、组合具体类和接口的方法:class SubClassName extends BaseClassName implements Interface1,Interface2{...body...}
2、接口方法须要在在子类或/和基类中定义:
- a) 若仅在子类中定义,则调用子类中方法。参考swim()&fly()
- b) 若仅在基类中定义,则调用基类中方法。参考fight()
- c) 若在基类和子类中均定义,则子类方法覆盖基类方法,调用子类方法。参考butterfly()
- d) 若均无定义,则编译能过,运行时异常。参考frogswim()