Java中有没有办法从该对象获取对象的父类的实例?
例如
public class Foo extends Bar {
public Bar getBar(){
// code to return an instance of Bar whose members have the same state as Foo's
}
}
最佳答案
没有内置的方法可以做到这一点。当然,您可以编写一种方法,该方法将使用Foo并创建已使用相关属性初始化的Bar。
public Bar getBar() {
Bar bar = new Bar();
bar.setPropOne(this.getPropOne());
bar.setPropTwo(this.getPropTwo());
return bar;
}
另一方面,继承的意思是Foo是Bar,所以您可以
public Bar getBar() {
return this;
}