如何获取对象父对象的实例
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
}
}
Is there a way in Java to get an instance of my object's parent class from that object?
ex.
public class Foo extends Bar {
public Bar getBar(){
// code to return an instance of Bar whose members have the same state as Foo's
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
没有内置的方法可以做到这一点。您当然可以编写一个方法,该方法将采用 Foo 并创建一个已使用相关属性初始化的 Bar。
另一方面,继承意味着 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.
On the other hand, what inheritance means is that a Foo is a Bar, so you could just do
长话短说:
如果您想返回一个副本,请在 Bar 上创建一个接收另一个 Bar 的复制构造函数。
Long story short:
If you want to return a copy, then create a copy constructor on Bar that receives another Bar.
this this 是 bar 的一个实例,简单的就是“return this;”但如果您需要一个不同的对象,也许您可以实现 java.lang.Clonable 和“return this.clone();”
this this is an instance of bar, the simple thing is just "return this;" but if you need a distinct object, perhaps you could implement java.lang.Clonable and "return this.clone();"
如果您的类扩展了 Bar,那么它就是 Bar 本身的一个实例。所以
应该这样做。
如果你想要一个“不同的实例”,你可以尝试:
If your class extends Bar, it is an instance of Bar itself. So
should do it.
If you want a "different instance", you can try:
由于 Foo is-a Bar,你可以这样做:
这只会返回当前对象的父实例。
Since Foo is-a Bar, you can do this:
This will only return the parent instance of current object.
您可以使用反射
You can use reflection