How to return the object that holds a class java
I have a class World that holds a class obj开发者_开发百科ect 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. 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. Then, you could use reflection to figure out exactly what that parent
's class is.
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
精彩评论