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
}
}
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
You can use reflection
Since Foo is-a Bar, you can do this:
This will only return the parent instance of current object.
Long story short:
If you want to return a copy, then create a copy constructor on Bar that receives another 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:
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();"