面向对象机试题

本文介绍了一个简单的水果箱管理系统,该系统使用Java实现,能够添加不同种类的水果如苹果和梨,并记录其重量和颜色等信息。此外,系统还支持从水果箱中取出指定位置的水果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.yenange.t2;
import java.util.ArrayList;
import java.util.List;

public class FruitTest {
// 3. 有一个水果箱(box),箱子里装有水果(fruit)。每一种水果都有不同的重量(weight)和颜色(color),
// 水果有:苹果(apple),梨(pear)。可以向水果箱(box)里添加水果(addFruit),也可以取出水果(getFruit)。
// 请编写java代码实现上述功能。
public static void main(String[] args) {
Box box = new Box();
box.addFruit(new Apple(25, "红色"));
box.addFruit(new Pear(30, "黄色"));
System.out.println("取之前的水果箱的总数量:"+box.num);
for (Fruit fruit : box.list) {
System.out.println(fruit);
}
System.out.println("/n取出来的水果是:");
Fruit fruit=box.getFruit(1);
System.out.println(fruit);
System.out.println("取之后的水果箱的总数量:"+box.num);
}
}

class Box {
List list = new ArrayList();
public int num = 0;

public Box() {
}

public void addFruit(Fruit f) {
list.add(f);
num++;
}

public Fruit getFruit(int index) {
Fruit f = list.get(index);
list.remove(f);
num--;
return f;
}
}

class Fruit {
private int weight;
private String color;

public Fruit(int weight, String color) {
this.weight = weight;
this.color = color;
}

public int getWeight() {
return weight;
}

public void setWeight(int weight) {
this.weight = weight;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

public String toString() {
return "水果名称:" + this.getClass().getSimpleName() + "/t颜色:"
+ this.getColor() + "/t重量:" + this.getWeight()+"克";
}
}

class Apple extends Fruit {
public Apple(int weight, String color) {
super(weight, color);
}
}

class Pear extends Fruit {
public Pear(int weight, String color) {
super(weight, color);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值