java中多态的一个应用

创建一个family接口,家里成员有说话的权利,写一个未实现的方法say()。

public interface family {
	void say();
}

 创建父亲类,实现接口family,实现说话权利的方法say()。

 

public class father implements family {


	public void say() {
		System.out.println("i am father");

	}

}

 

 创建母亲类,实现接口family,实现说话权利的方法say()。

public class mother implements family {

	public void say() {
		System.out.println("i am mother");

	}

}

 创建一个说话类,saying,里面控制家庭成员的说话。

 

public class saying {
	void say(father father){
		father.say();
	}
	
	void say(mother mother){
		mother.say();
	}
	
}

 测试类text

public class text {
	public static void main(String[] args){
		saying a = new saying();
		father person1 =new father();
		mother person2 = new mother();
		a.say(person1);
		a.say(person2);
	}
}

 结果为:

i am father
i am mother

这样有个麻烦,就是如果我又有一个son类实现接口family,那么son要说话,于是又要在saying中创建

void say(son son){

        system.out.println(“this is son”);

}

 

那么家庭成员多了,就会在saying类中写多个void say方法,传送不同的类参数,

如果把saying改成

public class saying {
	void say(family family){
		family.say();
	}
}

 

那么运行刚才同样的其他代码,运行结果同样。

这样就有个好处,无论家庭中添加多少成员,你都无需到saying去注册你的说话权利,就可以发言。

自然,这样的方法就使得程序的可扩展性和维护性增强了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值