如何获取我的对象的父对象的实例

ste*_*bot 2 java oop parent-child

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
     }

}
Run Code Online (Sandbox Code Playgroud)

Jac*_*son 5

没有内置的方法可以做到这一点。您当然可以编写一个方法,该方法将采用 Foo 并创建一个已使用相关属性初始化的 Bar。

  public Bar getBar() {
       Bar bar = new Bar();
       bar.setPropOne(this.getPropOne());
       bar.setPropTwo(this.getPropTwo());
       return bar;
  }
Run Code Online (Sandbox Code Playgroud)

另一方面,继承的意思是 Foo是一个Bar,所以你可以这样做

 public Bar getBar() {
      return this;
   }
Run Code Online (Sandbox Code Playgroud)