How to get an instance of my object's parent
13,009
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;
}
On the other hand, what inheritance means is that a Foo is a Bar, so you could just do
public Bar getBar() {
return this;
}
Author by
stevebot
http://www.codedforyou.com http://techmobilehub.blogger.com
Updated on June 04, 2022Comments
-
stevebot almost 2 years
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 } }
-
Erick Robertson over 13 yearsYes, all you have to do is write the method how you want it to work. If you just wanted it to
return this;
, then you should just doBar bar = foo;
You don't need a method to do that. -
Jacob Mattison over 13 yearsIt's not unreasonable to have a method that "casts" a Foo to a Bar as part of an API, say if you want certain clients to use your Foo only as if it were a Bar.