gpt4 book ai didi

java - 具有抽象函数的 Java 枚举有哪些非抽象版本不能做的事情? (即是否存在技术差异,或者只是一种模式?)

转载 作者:行者123 更新时间:2023-11-29 06:51:53 25 4
gpt4 key购买 nike

<分区>

好的,在this answer在堆栈上,答案的海报显示了一个示例,说明如何在枚举中使用抽象方法。我会在这里为后代重复这个答案,尽管稍作修改以更好地说明我的问题的基础。

考虑这个使用抽象方法的枚举:

public enum Vehicle {
CAR {
public String action() { return "DRIVE!"; }
},
TRUCK {
public String action() { return "DRIVE!"; }
},
BUS {
public String action() { return "DRIVE!"; }
},
TRACTOR {
public String action() { return "DRIVE!"; }
},
MOTORCYCLE {
public String action() { return "RIDE!"; }
},
BOAT {
public String action() { return "SAIL!"; }
},
AIRPLANE {
public String action() { return "PILOT!"; }
};

public abstract String action();
}

如您所见,由于“action”是一个抽象函数,因此每个元素都必须通过枚举的匿名子类定义覆盖。

将此与这个无抽象、功能相同的版本进行对比,后者甚至使用完全相同的 API:

enum Vehicle {
CAR,
TRUCK,
BUS,
TRACTOR,
MOTORCYCLE,
BOAT,
AIRPLANE;

public String action(){
switch(this)
{
case MOTORCYCLE : return "RIDE!";
case BOAT : return "SAIL!";
case AIRPLANE : return "FLY!";
default : return "DRIVE!";
}
}
}

在此示例中,您只需指定与默认值不同的特定情况。此外,它将值保存在一个漂亮、干净、可读的列表中,并减少了大量无关代码。

也许我遗漏了什么,但是抽象方法方法有技术优势吗?它究竟给了你什么非抽象版本没有的?它有任何额外的功能吗?

Note: I suspect the actual answer is because it's not really a function of an enum per se, but rather it's because the enum is compiled to a class and a class supports abstract functions.

However, I'm not exactly sure that's correct either because as others have shown, an enum compiles down to a static final class which means it can't be subclassed. Perhaps the compiler doesn't add the 'final' when using abstract functions. Not sure as I haven't been able to view generated output so I can't say for sure, but that would make sense.

But specifically for this question, is there anything an enum with an abstract function can do that a non-abstract version can't?

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