【JAVA学习路-think in java】p179:子类继承具体类和接口时,方法调用逻辑

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()
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值