gpt4 book ai didi

java - 将对象传递给抽象类?

转载 作者:行者123 更新时间:2023-11-30 11:35:03 26 4
gpt4 key购买 nike

我正在本地大学学习编程类(class)。我的讲师英语说得不是最好,所以有时很难理解他的要求。

我已经完成的作业的第一部分如下:一家机修店有 100 个顾客,每个顾客都是数组中的一个对象,数组中保存着各种数据。基类是服务,具体服务有四个派生类(轮胎、机油、散热器和刹车)。每个客户都分配了一项服务。打印所有客户的详细信息列表。

第二部分,我完全不明白他在问什么:如果最后一次服务是在一定数量的几个月前完成的,我们就会打印优惠券。我已经对日期进行了计算,如果服务是在一定时间之前完成的,我需要将服务数组中的一个对象传递给抽象优惠券类。他的确切指示如下:

Coupon is an Abstract parent class. The abstract class should have variable year, month and day. Make a Service Coupon extend the Abstract coupon class. Several child classes - BrakeService Coupon, Tire Coupon, Engine Oil Coupon, Radiator Coupon extend the Service Coupons. Add an Expiry date to a random date in 2013 and Make it final in the constructor of the objects. The service object calls the coupon passing the service object. The coupon determines the type of service object it receives and accordingly prints the message. This should be simple.

这是我认为它要求的(纯粹是为了证明我们知道如何使用抽象和继承的练习):

http://www.java-forums.org/attachments/new-java/4632-passing-object-abstract-class-rtc3ild.png

我应该将对象传递给抽象类吗?如果是这样,我是否应该使用我的主类并将其作为抽象优惠券类的扩展?

我现在拥有的是扩展具体 Service 类的抽象 Coupon 类,其中 ServiceCoupon 类扩展了 Coupon,还有四个扩展它的具体类。我不确定如何调用 Coupon 类或将其基类中的对象传递给它。

对不起,我不能更清楚。我也不知道他想要什么。

编辑: **我遇到的主要问题是我想将一个对象传递给另一个抽象类。我无法实例化此类,因为它是抽象的,所以我不知道如何将对象传递给该方法。

最佳答案

我想他想要的是工厂模式,即你传入你的Service,工厂判断Service的类型,然后返回合适的Coupon 实现。基于 Map 的东西可能会成功

final Map<Class<? extends Service>, Class<? extends Coupon>> myMap;

public Coupon getCoupon(final Service service) {
final Coupon coupon = myMap.get(service.getClass()).newInstance();
//init stuff
return coupon;
}

显然,只有当您的 Coupon 有一个 noargs 构造函数时,这才有效。

关于java - 将对象传递给抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15324569/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com