编写一个小的程序,其中定义一些接口、类、抽象类,定义它们的成员(字段及方法)等
编写一个小的程序,其中定义一些接口、类、抽象类,定义它们的成员(字段及方法), 要求使用使用setter/getter, static, final, abstract,@Override等语法要素,并写一个main函数来使用它们。这些类、接口可以是围绕以下选题之一
飞翔世界:来一次飞翔接力(即多个可飞翔的对象依次调用);
动物世界:来一次吃西瓜大赛;
图书馆:模拟一天的借阅过程;
学校:模拟选课过程;
等等
我选的是动物世界
// An highlighted block
var foo = 'bar';
package eatcompetition;
public class EatCompetition {
public static void main(String[] args) {
// TODO Auto-generated method stub
SmallAnimal a1 = new SmallAnimal();
a1.setType("Mickey Mouse");
a1.setnumOfMelon(0.5);
SmallAnimal a2 =new SmallAnimal();
a2.setType("Tom Cat");
a2.setnumOfMelon(1);
SmallAnimal a3 = new SmallAnimal();
a3.setType("Teddy Dog");
a3.setnumOfMelon(3);
BigAnimal b1 = new BigAnimal();
b1.setType("Tiger");
b1.setnumOfMelon(10);
BigAnimal b2 = new BigAnimal();
b2.setType("Elephant");
b2.setnumOfMelon(50);
BigAnimal b3 = new BigAnimal();
b3.setType("Whale");
b3.setnumOfMelon(150);
System.out.println("吃西瓜比赛开始");
a1.eatwatermelon();
a1.stop();
a1.sleep();
a2.eatwatermelon();
a2.stop();
a2.sleep();
a3.eatwatermelon();
a3.stop();
a3.sleep();
b1.eatwatermelon();
b1.stop();
b1.sleep();
b2.eatwatermelon();
b2.stop();
b2.sleep();
b3.eatwatermelon();
b3.stop();
b3.sleep();
}
}
//定义接口,包含吃西瓜和停止
interface Eatable{
public void eatwatermelon();
public void stop();
}
//定义动物类,包含吃和睡
abstract class animal {
public void eat(){}
public void sleep(){}
}
//小型动物,继承动物父类,同时要参加吃西瓜比赛
class SmallAnimal extends animal implements Eatable{
private String type;
private double numOfMelon;
public String getType(){
return type;
}
public void setType(String type){
this.type = type;
}
public double getnumOfMelon(){
return numOfMelon;
}
public void setnumOfMelon(double numOfMelon){
this.numOfMelon = numOfMelon;
}
public static final int maxnumOfMelon=3;
//@Override
public void eatwatermelon(){
System.out.println(type+"开始吃西瓜");
}
public void stop(){
System.out.println(type+"吃了"+numOfMelon+"个西瓜");
System.out.println("吃不下了");
}
@Override
public void sleep(){
System.out.println("吃饱了睡觉去");
}
}
//大型动物,跟小型动物定义一样
class BigAnimal extends animal implements Eatable{
private String type;
private double numOfMelon;
public String getType(){
return type;
}
public void setType(String type){
this.type = type;
}
public double getnumOfMelon(){
return numOfMelon;
}
public void setnumOfMelon(double numOfMelon){
this.numOfMelon = numOfMelon;
}
public static final int maxnumOfMelon=100;
//@Override
public void eatwatermelon(){
System.out.println(type+"开始吃西瓜");
}
public void stop(){
System.out.println(type+"吃了"+numOfMelon+"个西瓜");
System.out.println("吃不下了");
}
@Override
public void sleep(){
System.out.println("吃饱了睡觉去");
}
}
程序运行结果如下