一、首先创建一个接口类,代码如下:
public interface GrandFatherInterface {
public void say();
}
二、然后创建两个类来继承此接口分别是BigSon和SecondSon,其代码如下
public class Bigson implements GrandFatherInterface{
public void say() {
// TODO 自动生成的方法存根
System.out.println("I am bigson");
}
}
public class SecondSon implements GrandFatherInterface {
@Override
public void say() {
// TODO 自动生成的方法存根
System.out.println("I am secondson");
}
}
三、然后创建一个Control类来处理事件
public class Controller {
public GrandFatherInterface control(String i) {
if(i.equalsIgnoreCase("bigson"))
{
return new Bigson();
}
else if(i.equalsIgnoreCase("secondson"))
{
return new SecondSon();
}
else {
return null;
}
}
}
四、最后创建测试类
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO 自动生成的方法存根
System.out.println("请输入bigson或者secondson");
Scanner scanner=new Scanner(System.in);
String name=scanner.nextLine();
scanner.close();
Controller controller=new Controller();
GrandFatherInterface grandFatherInterface=controller.control(name);
grandFatherInterface.say();
}
}
五、在eclipse中一个运行结果如下: