java调料包数据(看案例能猜到实现了什么功能吗?)

啥也不说…看案例,能猜到这样做是为了实现什么功能吗?嘻嘻嘻

import java.util.HashMap;

interface Person{

	public void talk(HashMap context);
}
class Fjy implements Person{
	String name="傅靖耀";
	
	@Override
	public void talk(HashMap context) {//要求是String的参数
		// TODO Auto-generated method stub
		String str = null;
		if(context.containsKey("Fjy")) {
			str=(String) context.get("Fjy");
			str=str+"!!!";
		}
		System.out.println(this.name+"说了一些话:"+str);
	}
	
}
class Zyl implements Person{
	String name="张杨磊";
	
	@Override
	public void talk(HashMap context) {//要求是Int的参数
		// TODO Auto-generated method stub
		int i = 0;
		if(context.containsKey("Zyl")) {
			i= (int) context.get("Zyl");
			i++;
		}
		System.out.println(this.name+"说了一些话:今天干了"+i+"份任务");
	}
	
}
class Hzx implements Person{
	String name="侯张旭";

	@Override
	public void talk(HashMap context) {//要求是Boolean的参数
		// TODO Auto-generated method stub
		boolean b = false;
		if(context.containsKey("Hzx")) {
			b=(boolean) context.get("Hzx");
			
		}
		System.out.println(this.name+"说了一些话:我说的都是"+b+"的真理啊");
	}
	
}

class ZuZhuangZhe{//组装者
	HashMap hash;
	
	ZuZhuangZhe(){
		hash=new HashMap();
		hash.put("傅靖耀", "Fjy");
		hash.put("张杨磊", "Zyl");
		hash.put("侯张旭", "Hzx");
		
		
	}
	public Person setZuZhuangZhe(String name) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Class c=Class.forName((String) hash.get(name));
		Person p=(Person) c.newInstance();
		return p;
	}
	public void talkFor(Person p,HashMap type) {
		p.talk(type);
	}
}
public class ContextDemo {

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		// TODO Auto-generated method stub
		ZuZhuangZhe z=new ZuZhuangZhe();
		HashMap type=new HashMap();
		type.put("Fjy", "GirlFriend");
		type.put("Zyl",1);
		type.put("Hzx",true);
		
		Person p1=z.setZuZhuangZhe("傅靖耀");
		z.talkFor(p1,type);
		Person p2=z.setZuZhuangZhe("张杨磊");
		z.talkFor(p2, type);
		Person p3=z.setZuZhuangZhe("侯张旭");
		z.talkFor(p3, type);
	}

}

猜不到给点提示:向下拉(别拉到底)















































提示执行结果:
在这里插入图片描述

最终答案在下面:看看你是否已经猜对了!















































需要实现的结果是:在栗子中有三个实例类,Fjy,Zyl,Hzx,他们都有不一样的talk方法的参数,
Fjy的talk参数是talk(String str);
Zyl的talk参数是talk(int i);
Hzx的talk参数是talk(Boolean b);
三个参数都是不一样的,我又想要通过多态来实现这些方法,以上代码就做来这个事情,通过一个HashMap散列表实现了功能。

猜你喜欢

转载自blog.csdn.net/weixin_43299461/article/details/86556121