需求:编写一个程序(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为种子 int n= rnd.nextInt(100); // 返回0~99之间的随机数 完整代码如下: import java.util.Random; public class Fruit { void eat() { System.out.println("Eat "+this.getClass()); } public static void main(String args[]){ Fruit[] fruits=new Fruit[20];//定义对象 Random rnd=new Random(1);//设置初始化数据为1 for(int i=0;i<20;i++){ int num=rnd.nextInt(3);//产生0-2之间的数据 Fruit fruit = null; switch(num){//根据随机数,定义不同的对象 case 0: fruit=new Fruit(); break; case 1: fruit=new Orange(); break; case 2: fruit=new Apple(); break; } fruits[i]=fruit; } for(Fruit f:fruits){//遍历数组,调用eat方法 f.eat(); } } } class Orange extends Fruit{ void eat(){ System.out.println("The orange tastes a little sour"); } } class Apple extends Fruit{ }之前犯了一个错误,加了一个package lab3的声明。后来Java Fruit时提示找不到主类,还以为环境变量出问题了。其实是因为找不到这个这个包。