在testO包中
// 主程序TestInterface.java
package testO;
import testT.*;
public class TestInterface {
public static void main(String[] args) {
Students stu = new Students("学成餐");
stu.eat();
Teachers terche = new Teachers("教师餐");
terche.eat();
Parents parent = new Parents("家长餐");
parent.eat();
Car car = new Car();
car.runTime(10.5, 3.0, 5.3);
Plant plant = new Plant();
plant.runTime(10.5,3.0,5.3);
}
}
// 接口facePerson .java
package testO;
public interface facePerson {
public String free = "免费";
public void eat();
public void sleep();
}
// Parents.java 类
package testO;
public class Parents implements facePerson{
private String food;
public Parents() {}
public Parents(String food) {
this.food = food;
}
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("家长食堂:"+this.food);
}
@Override
public void sleep() {
// TODO Auto-generated method stub
System.out.println("家长公寓");
}
public void setFood(String food) {
this.food = food;
}
public String getFood() {
return food;
}
}
// 接口Students .java
package testO;
public class Students implements facePerson{
private String food;
public Students() {}
public Students(String food) {
this.food = food;
}
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("学生食堂:"+ this.food + facePerson.free);
}
@Override
public void sleep() {
// TODO Auto-generated method stub
System.out.println("学生宿舍");
}
public void setFood(String food) {
this.food = food;
}
public String getFood() {
return food;
}
}
// Teachers .java 类
package testO;
public class Teachers implements facePerson{
private String food;
public Teachers() {}
public Teachers(String food) {
this.food = food;
}
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("教师食堂:"+this.food);
}
@Override
public void sleep() {
// TODO Auto-generated method stub
System.out.println("教师公寓");
}
public void setFood(String food) {
this.food = food;
}
public String getFood() {
return food;
}
}
在testT包中
// 接口 Computed.java
package testT;
public interface Computed {
public void runTime(double a,double b,double c);
}
// 类 Car.java
package testT;
public class Car implements Computed{
@Override
public void runTime(double a, double b, double c) {
// TODO Auto-generated method stub
double time = a*b/c;
System.out.println("car运行的时间:"+ time);
}
}
// 类 Plant.java
package testT;
public class Plant implements Computed{
@Override
public void runTime(double a, double b, double c) {
// TODO Auto-generated method stub
double time = (a+b)/c;
System.out.println("Plant运行时间:"+ time);
}
}
运行的结果: