Coursera 深入理解Java语言 week5_作业 定义类与接口

1.作业要求:

编写一个小的程序,其中定义一些接口、类、抽象类,定义它们的成员(字段及方法),要求使用使用setter/getter, static, final, abstract,@Override等语法要素,并写一个main函数来使用它们(创建多个对象并调用它们的方法),可以使用数组、随机数等。这些类、接口可以是围绕以下选题之一

飞翔世界:来一次飞翔接力(即多个可飞翔的对象依次调用);

动物世界:来一次吃西瓜大赛;

图书馆:模拟一天的借阅过程;

学校:模拟选课过程;

等等

要求写个简要说明。

2.简要说明:

Animal World:a  watermelon-eating contest

定义一个Eat_watermelon接口,定义类animal、Contest_begin实现该接口,定义类Contestant继承类animal,在Contestant中利用random产生随机数,在限定时间内产生一个吃完西瓜用时的随机数。最后在主类中,通过比较随机数的大小得到吃瓜比赛的冠军。


3.Java代码:

import java.util.Random;
/* 
 * java practice about class and interface in coursera
 * theme 
 * Animal World: watermelon-eating contest;
 */

interface Eat_watermelon{
	void eat();
}

abstract class animal implements Eat_watermelon{
	public void eat() {
		System.out.println("begin contest!");
		System.out.println("finish contest!");
	}
}//@override

class Contest_begin implements Eat_watermelon{
	protected static final int  total_time = 20;
	public void eat() {
		System.out.println("The total time of this contest is "+total_time+ " minutes.");
		System.out.println("Now, the contestants are ready for eating!");
	}
}

class Contestant extends animal{
	private String animal;
	public void setter(String animal) {
		this.animal = animal;
	}
	public String getter() {
		return animal;
	}
	public int RandomEaten(){
		Random random = new Random();
		int used_time = Math.abs(random.nextInt())%20;
		return used_time;
	}// generate a used_time by random 
	
}



public class week5 {
	public static void main(String[] args) {
		Contest_begin begin = new Contest_begin();
		begin.eat();
		System.out.println("The watermelon-eating contest is begining!");
		String animal1 = "horse";
		String animal2 = "cow";
		System.out.println("The contestants of this contest are "+animal1+" and "+animal2+".");
		Contestant  contestant1  = new Contestant();
		contestant1.setter(animal1);
		int time1 = contestant1.RandomEaten();
		System.out.println("Contestant "+animal1+" finish eating watermelon with "+time1+" minutes.");
		Contestant  contestant2  = new Contestant();
		contestant2.setter(animal2);
		int time2 = contestant2.RandomEaten();
		System.out.println("Contestant "+animal2+" finish eating watermelon with "+time2+" minutes.");
		
		if(time1 == time2) {
			System.out.println("The winner of this watermelon-eating contest are both "+animal1+" and "+animal2+".");
		}else if(time1 < time2) {
			System.out.println("The winner is "+animal1+".");
		}else{
			System.out.println("The winner is "+animal2+".");
		}
		
		System.out.println("The watermelon-eating contest is ending!");
	}	
}
       	




你可能感兴趣的:(Java学习)