Java 如何获取对象父对象的实例
Java中有没有一种方法可以从该对象中获取对象父类的实例 前Java 如何获取对象父对象的实例,java,oop,parent-child,Java,Oop,Parent Child,Java中有没有一种方法可以从该对象中获取对象父类的实例 前 没有内置的方法可以做到这一点。您当然可以编写一个方法,该方法将接受一个Foo并创建一个用相关属性初始化的条 public Bar getBar() { Bar bar = new Bar(); bar.setPropOne(this.getPropOne()); bar.setPropTwo(this.getPropTwo()); return bar; } 另一方面,
没有内置的方法可以做到这一点。您当然可以编写一个方法,该方法将接受一个Foo并创建一个用相关属性初始化的条
public Bar getBar() {
Bar bar = new Bar();
bar.setPropOne(this.getPropOne());
bar.setPropTwo(this.getPropTwo());
return bar;
}
另一方面,继承意味着一个Foo就是一个Bar,所以你可以这样做
public Bar getBar() {
return this;
}
长话短说:
return this;
若要返回副本,请在接收另一个Bar的Bar上创建副本构造函数
public Bar(Bar that) {
this.a = that.a;
this.b = that.b;
...
}
这是一个例子吧,简单的事情就是返回这个;但是如果您需要一个不同的对象,也许可以实现java.lang.Clonable并返回this.clone 如果您的类扩展了Bar,那么它就是Bar本身的一个实例。所以
public Bar getBar() {
return (Bar) this;
}
我应该这样做。
如果需要其他实例,可以尝试:
public Bar getBar() {
return (Bar) this.clone();
}
由于Foo是一个酒吧,您可以这样做:
return this;
这将只返回当前对象的父实例。您可以使用反射
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();
}
}
你就不能退这个吗-1因为不清楚。此外,如果目的只是归还该文件;,你不需要一个函数来实现它。@Erick Robertson:你不需要费心去读方法中的代码和注释。是的,我读了。评论准确地描述了你应该做什么。创建并返回其成员具有相同状态的Bar的实例。我不知道怎么做,因为你没有包括Bar或Foo的定义。老实说,评论不清楚是否需要一个新实例。是的,你所要做的就是编写你希望它如何工作的方法。如果你只是想让它归还这个;,那么你应该只做Bar=foo;你不需要一个方法来做到这一点。让一个方法将一个Foo作为API的一部分强制转换到一个Bar也不是不合理的,比如说,如果你想让某些客户使用你的Foo,就好像它是一个Bar一样。
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();
}
}