【问题标题】:Initialize parameters by enum type通过枚举类型初始化参数
【发布时间】:2017-02-16 23:41:29
【问题描述】:

所以我在我的作业中分配了一个任务,如下所示:

AirCraft 是一种 PublicTransportation,它还具有以下内容:类类型(枚举类型可以是:直升机、航空公司、滑翔机或气球)和维护类型(枚举类型可以是:每周、每月或每年) .

我们还没有真正了解枚举是什么,但我正在尝试了解它。我知道它们是常量列表(静态和最终)。我只是不知道如何在我的驱动程序类中初始化枚举参数。

public class Aircraft extends PublicTransportation
{

    private enum ClassType {HELICOPTER, AIRLINE, GLIDER, BALLOON}
    private enum MaintType {WEEKLY, MONTHLY, YEARLY}

    private ClassType cType;
    private MaintType mType;

    public Aircraft()
    {
        super();
        cType = null;
        mType = null;
    }

    public Aircraft(double ticketPrice, int numOfStops, ClassType cType, MaintType mType)
    {
        super(ticketPrice, numOfStops);
        this.cType = cType;
        this.mType = mType;     
    }

    public Aircraft(Aircraft anAircraft)
    {
        super(anAircraft.getTicketPrice(), anAircraft.getNumOfStops());
        this.cType = anAircraft.cType;
        this.mType = anAircraft.mType;
    }
}

这是我的驱动程序类的一部分:

package Driver;
import CityBus.CityBus;
import CityBus.Metro;
import CityBus.Tram;
import Ferry.Ferry;
import Aircraft.Aircraft;
import Aircraft.Aircraft;
import PublicTransportation.PublicTransportation;

public class Driver 
{



    public static void main(String[] args) 
    {

        Aircraft ac1 = new Aircraft(1,2, GLIDER, Aircraft.GLIDER);

你如何初始化一个枚举类型?

【问题讨论】:

  • 你不能,因为枚举在 Aircraft 类中被声明为私有。所以只有飞机可以访问它们。将它们移到类之外,在它们自己的 Java 源文件中,就像使用常规顶级类一样,并使用 ClassType.HELICOPTER。

标签: java enums


【解决方案1】:

将声明更改为

public static enum ClassType {HELICOPTER, AIRLINE, GLIDER, BALLOON}
public static enum MaintType {WEEKLY, MONTHLY, YEARLY}

在你的驱动类中

Aircraft ac1 = new Aircraft(1,2, Aircraft.ClassType.GLIDER, Aircraft.MaintType.WEEKLY);

我通过猜测滑翔机每周进行维护来解决了调用 Aircraft 构造函数的问题 :-)

如果您不想输入完全限定的枚举常量,您可以在文件顶部import static:

import static Aircraft.ClassType.*;
import static Aircraft.MaintType.*;

然后使用没有限定的枚举常量。然而,正如@LewBloch 在评论中指出的那样,静态导入会降低代码的可读性。我自己对它们的使用有些矛盾。在特定情况下,如果代码中有足够的文档/警告,它们会很有用。我一般会避开它们。我将它们包括在内只是为了完整性,而不是作为认可。

【讨论】:

  • 有时静态重要的枚举常量很好,但如果你导入类,代码更清晰。 <class>.<constant> 不是完全限定名称。 <package>.<class>.<constant> 是一个完全限定的名称。
  • 是的,我对静态导入很矛盾。我会将您的评论添加到帖子中。
猜你喜欢
  • 2012-09-15
  • 2014-08-02
  • 2011-10-21
  • 1970-01-01
  • 2021-01-23
  • 2011-04-18
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
相关资源
最近更新 更多