- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
<分区>
好的,在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?
我是一名优秀的程序员,十分优秀!