如何获取我的对象的父对象的实例 [英] How to get an instance of my object's parent
本文介绍了如何获取我的对象的父对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Java 中有没有办法从该对象中获取我的对象的父类的实例?
Is there a way in Java to get an instance of my object's parent class from that object?
例如.
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.
There's no built-in way to do this. You can certainly write a method that will take a Foo and create a Bar that's been initialized with the relevant properties.
public Bar getBar() {
Bar bar = new Bar();
bar.setPropOne(this.getPropOne());
bar.setPropTwo(this.getPropTwo());
return bar;
}
另一方面,继承意味着Foo 是 Bar,所以你可以这样做
On the other hand, what inheritance means is that a Foo is a Bar, so you could just do
public Bar getBar() {
return this;
}
这篇关于如何获取我的对象的父对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文