假设我有一个类如下:
private class ComparableElement extends Element implements Comparable<ComparableElement> {
@Override
public int compareTo(ComparableElement o) {
return getName().compareTo(o.getName());
}
}
其中 Elements 定义如下:
public class Element {
protected String name;
protected String category;
public Element() {
super();
}
public Element(String _name, String _category) {
super();
this.name = _name;
this.category = _category;
}
public String getName() {
return name;
}
}
那么,如果我有一个 Element 对象,将该 Element 对象转换为 ComparableElement 实例的最佳实践是什么?类似的东西:
Element e;
...
ComparableElement ce = (ComparableElement)e;
只是这行不通......
最佳答案
您可以创建新的构造器ComparableElement
:
public ComparableElement (Element element )
{
//Here you get all the data from the element and set it to this object.
}
关于java - 将父类实例对象转换为子类实例对象的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25034188/