具体,创建一个名称为Person的接口,在接口中定义两个方法sayHello()和sayBye()。然后,创建两个实现了Person接口的类Chinese和American。在Chinese类中,两个方法分别输出“你好,见到你很高兴!”和“再见!”;在American类中,两个方法分别输出“Hi,nice to meet you!”和“Goodbye!”。另外再创建一个带有main()方法的InterfaceDemo类,在main()中声明Person类型的两个引用c和a,并分别为它们创建Chinese和American类的实例,然后依次访问它们的sayHello()和sayBye()方法,查看最后的输出结果。
public class Test_6_2InterfaceDemo { public static void main(String[] args) { Test_6_2Chinese c = new Test_6_2Chinese(); Test_6_2American a = new Test_6_2American(); c.sayHello(); c.sayBye(); a.sayHello(); a.sayBye(); } }
public interface Test_6_2Person { void sayHello(); void sayBye(); }
public class Test_6_2Chinese implements Test_6_2Person { @Override public void sayHello() { System.out.println("你好,遇见你很高兴~"); } @Override public void sayBye() { System.out.println("再见!"); } }
public class Test_6_2American implements Test_6_2Person { @Override public void sayHello() { System.out.println("Hello nice to me too~"); } @Override public void sayBye() { System.out.println("Goodbye"); } }