求一个用到interface接口的Java的程序

要求简单易明白
2025-03-03 18:49:31
推荐回答(1个)
回答1:


/**
 * 定义一个学校类(接口)
 * @author Tercel
 *
 */
public interface XueXiao {

/**
 * 获取学校的总人数
 * @return
 */
public int getTotal();
}


/**
 * 清华大学
 * @author Tercel
 *
 */
public class QingHuaDaXue implements XueXiao {
private int total;
public QingHuaDaXue(int total) {
super();
this.total = total;
}

@Override
public int getTotal() {
return total;
}

@Override
public String toString() {
return "清华大学人数 [total=" + total + "]";
}
}



/**
 * 哈弗大学
 * @author Tercel
 *
 */
public class HaFuDaXue implements XueXiao {
private int total = 2000;
public HaFuDaXue(int total) {
super();
this.total = total;
}

@Override
public int getTotal() {
return total;
}

@Override
public String toString() {
return "哈弗大学人数: [total=" + total + "]";
}
}


这个是测试类
public class Test {
public static void main(String[] args) {
                XueXiao xx = new QingHuaDaXue(1000);    //声明一个变量,变量指向它的子类
XueXiao xx1 = new HaFuDaXue(2000);//声明一个变量,变量指向它的子类

System.out.println(xx);
System.out.println(xx1);

}
}