How to get an instance of my object's parent

最后都变了- 提交于 2019-12-11 05:14:40

问题


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
     }

}

回答1:


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;
   }



回答2:


Long story short:

return this;

If you want to return a copy, then create a copy constructor on Bar that receives another Bar.

public Bar(Bar that) {
    this.a = that.a;
    this.b = that.b;
    ...
}



回答3:


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();"




回答4:


If your class extends Bar, it is an instance of Bar itself. So

public Bar getBar() {
  return (Bar) this;
}

should do it. If you want a "different instance", you can try:

public Bar getBar() {
   return (Bar) this.clone();
}



回答5:


Since Foo is-a Bar, you can do this:

return this;

This will only return the parent instance of current object.




回答6:


You can use reflection

    package com;

    class Bar {

        public void whoAreYou(){
            System.out.println("I'm Bar");
        }

    }

    public class Foo extends Bar{

        public void whoAreYou() {
            System.out.println("I'm Foo");
        }

        public Bar getBar() {
            try {
                return (Bar)this.getClass().getSuperclass().newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            throw new RuntimeException();
        }

        public static void main() {
            Foo foo = new Foo();
            foo.whoAreYou();
            foo.getBar().whoAreYou();
        }
    }


来源:https://stackoverflow.com/questions/3909258/how-to-get-an-instance-of-my-objects-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!