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;
}
关于java - 如何获取我的对象的父对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3909258/