How to get an instance of my object's parent

2019-07-25 13:52发布

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
     }

}

6条回答
对你真心纯属浪费
2楼-- · 2019-07-25 14:12

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;
   }
查看更多
萌系小妹纸
3楼-- · 2019-07-25 14:19

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();
        }
    }
查看更多
叼着烟拽天下
4楼-- · 2019-07-25 14:26

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

return this;

This will only return the parent instance of current object.

查看更多
Explosion°爆炸
5楼-- · 2019-07-25 14:27

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;
    ...
}
查看更多
我命由我不由天
6楼-- · 2019-07-25 14:28

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();
}
查看更多
做个烂人
7楼-- · 2019-07-25 14:29

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

查看更多
登录 后发表回答