简体   繁体   English

如何返回持有类java的对象

[英]How to return the object that holds a class java

I have a class World that holds a class object named Player and I would like to be able to inside Player to be able to create an object of the class holding the object. 我有一个World类,其中包含一个名为Player的类对象,并且我希望能够在Player内部创建一个包含该对象的类的对象。 Does what I am saying make sense? 我说的话有意义吗? Is what im saying possible? 我说的可能吗?

edit:Also Player is abstract and I get an error in the child class when I put some of your code in 编辑:也播放器是抽象的,当我将一些代码放入子类时,我在子类中收到错误

You could make a reference named parent , and assign it upon creation. 您可以创建一个名为parent的引用,并在创建时进行分配。 Then, you could use reflection to figure out exactly what that parent 's class is. 然后,您可以使用反射来确切地确定该parent级的类是什么。

public class Player{
    private Object parent;
    public Player(Object parent){
        this.parent = parent;
    }
    public Class getParentClass(){
        return parent.getClass();
    }
}

You can just give the world object to the constructor of player 您可以将世界对象交给玩家的构造函数

public class World{
  public World(){
    new Player(this);
  }
}
public class Player{
  private World world;
  public Player(World world){
    this.world = world;
  }
}

now you can use the world inside the player with world 现在您可以将玩家内的worldworld

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM