您的位置:首页 > 编程语言 > Java开发

java中类的继承性和多态性实例

2015-12-04 12:45 477 查看
题目描述:

编写一个程序(Fruit.java),其中有三个类:Fruit,Orange、Apple,其中,Orange、Apple是Fruit的子类:

(1)类Fruit有eat()和main()(入口函数)两个方法,没有数据域,其中eat()中用this.getClass()显示当前对象的类名。 main()中随机生成这三种对象(用for和switch语句),共生成20个(把20定义为常量)对象,并用Fruit数组存放,然后用foreach循环对所有这些对象执行eat。

(2)类Orange有一个方法eat,没有数据域,其中,eat()显示" The orange tastes a little sour"。

(3)类Apple没有数据域和方法。

提示: 随机数产生方法

import java.util.Random;
Random rnd=new Random(50); //
局部变量rnd初始化50为种子
intn= rnd.nextInt(100); //返回0~99之间的随机数

参考输出:



代码:

import java.util.*;
import  java.util.Random;

class Fruit{
public void eat()
{
System.out.println("Eat " + this.getClass());
}

public static void main(String[] args){
final int end = 20;
Fruit fruits[] = new Fruit[end];

//产生种子:注意要用当前时间做种子才能产生变化的随机数,不然每次是固定的一个数!
Random rnd= new Random(System.currentTimeMillis());
for(int i=0;i < end;i++)
{
int n= rnd.nextInt(3); //产生0~2之间的随机数
switch(n)
{
case 0:
fruits[i] = new Fruit();
break;
case 1:
fruits[i] = new Orange();
break;
case 2:
fruits[i] = new Apple();
break;
default:
break;
}
}
for(Fruit f:fruits)
{
f.eat();
}
}
}

class Orange extends Fruit{
//@override
public void eat()
{
System.out.println("The orange tastes a little sour");
}

}

class Apple extends Fruit{
}


运行结果截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: