qwo*_*p72 7 java inheritance enums interface
现在,我有一个现有的类,我想将其重构为一个Enum。该类当前扩展了另一个类,该类来自外部库。我仍然想从扩展类的某些逻辑中受益,同时希望进行重构。应该怎么做?
在Java中,一个enum类不能扩展另一个类,而可以实现interface。或将其重构为枚举的想法已经是错误的吗?让我在下面的示例代码中展示它。
假设一个现有的类Existing正在扩展另一个类Parent,并且Parent类来自外部库,它不是接口。
class Existing extends Parent{
public static final Existing A = new Existing(...);
....
public static final Existing Z = new Existing(...);
public Existing(Srting attr1, String attr1){
super(attr1, attr2);
}
public Existing(String attr1){
super(attr1);
}
}
Run Code Online (Sandbox Code Playgroud)
这个想法是让那些静态的final字段成为Enums,例如:
enum NewDesign{
A(attr1, attr2),
B(attr1),
C(attr1, attr2)
//...;
//constructor etc.
//...
}
Run Code Online (Sandbox Code Playgroud)
并可能在需要时添加新的额外属性,如下所示:
enum NewDesign{
A(attr1, attr2, newAttr),
B(attr1, newAttr),
C(attr1, attr2, newAttr),
//...
//constructor etc.
//...
}
Run Code Online (Sandbox Code Playgroud)
If the main change that you need is to create an enum to get rid of static final fields, the easiest way to go about it is to create a different, enum type with initialized instances:
enum ExistingEnum {
A("attr1", "attr2"),
Z("attr");
private final Existing existing;
ExistingEnum(String attr1) {
this.existing = new Existing(attr1);
}
ExistingEnum(String attr1, String attr2) {
this.existing = new Existing(attr1, attr2);
}
public Existing getExisting() {
return existing;
}
}
Run Code Online (Sandbox Code Playgroud)
Depending on how you're using your Existing class currently, you may still be able to change it to an enum. In the following example, I expose an instance of Parent on the enum, assuming code using Existing can be changed to call Existing.A.getParent().parentMethod()...
enum Existing {
A("attr1", "attr2"),
Z("attr");
private final Parent existing;
Existing(String attr1) {
this.existing = new ParentImpl(attr1);
}
Existing(String attr1, String attr2) {
this.existing = new ParentImpl(attr1, attr2);
}
public Parent getParent() {
return existing;
}
// only needed if logic is overridden
private static class ParentImpl extends Parent {
public static final Existing A = "";
public static final Existing Z = "";
public ParentImpl(String attr1, String attr2) {
super(attr1, attr2);
}
public ParentImpl(String attr1) {
super(attr1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
214 次 |
| 最近记录: |