接口与继承

1、通过继承实现

public class People{      //一个人生下来就可能具备这些能力这是大多数人通用的能力
	void say(){};
	void run(){};
	void eat(){};	
	.
	.
	.
}

我们根据这些通用的特征做一些调整

public class SuperMan extends People{
	void fly(){}           //他是一个超人,处理正常的能力,他还会飞
}

还有一类人

public class DisabledSay{     //他不能说话,及时只与people缺少了一个能力,我们也无法继承。
	void run(){};
	void eat(){};	
	.
	.
	.
}
public class DisabledRun{     //他不能跑
	void say(){};
	void eat(){};	
	.
	.
	.
}

这种情况继承不能满足所有人

但是通过接口,我们将各种能力拆分

	public interface Runable();
	public interface eatable();
	public interface sayable();
	//只要实现了这个能力就获得该能力
	public class DisabledRun implements eatable,sayable{
	
	}

举办了一个生物唱歌大赛

public class Biologysingsing{    //举办了一个生物唱歌大赛
	sayable singsing;
	void match(sayable say)       //只要能发出声音就能参加
	{
	this.singsing = say;
	}
}

所以动物也来了

public class brid implements sayable{
}

若是用继承的方案,人类只能开人类的演唱会。动物若想开,还需要再给动物举办

	public class singsing{
		People people;
		void match(people man)       //只要能发出声音就能参加
	{
		this.people= man;
	}
	void sing()
	{
		people.say();
	}
}

总结:1.接口在有些情况下比继承使用更灵活,可大大降低开发效率。
2. 接口还可以降低程序件的耦合型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值