Reputation: 245
I am still quite inexperienced with using Java, and would like to solve this stumbling block:
I have created two classes to be used in a rigid body dynamics simulation, called:
RigidBody
RigidBodyElement
The plan is to create a RigidBody
object. This object will be comprised of many little RigidBodyElement
objects. So, inside RigidBody
, there will be a single array of type RigidBodyElements
to contain all of the rigid body elements.
As for RigidBodyElement
, there will be a field variable containing the coordinates of the element relative to a fixed point on the RigidBody
object. This variable will be called relativeCoordinates
.
That much is fine. The problem arises when we want to find the absolute coordinates of each element, absoluteCoordinates
. To find that, we would need to add the rotated relativeCoordinates
of RigidBodyElement
to the coordinates of the overall rigid body, RigidBody
. i.e. writing a function in RigidBodyElement
, such that when an instance of RigidBodyElements
calls this function, it will get some of the information from the instance of the class RigidBody
in which this element is instantiated.
I currently have no idea how to define a function for an object to refer to another object that has instantiated the first object.
Upvotes: 0
Views: 54
Reputation: 11484
another approach is that you could make RigidBodyElement an Inner class.
public class RigidBody{
private double x, y;
private List<RigidBodyElement> elements = new ArrayList<>();
public RigidBody(){
elements.add(new RigidBodyElement(50,20));
}
public class RigidBodyElement(){
private double x, y;
public RigidBodyElement(double x, double y){
this.x=x;
this.y=y;
}
public double getAbsoluteX(){
//RigidBody.this references the RigidBody which created this element
return RigidBody.this.x + this.x;
}
}
}
Upvotes: 3
Reputation: 16651
You can use the this
keyword.
So you should have a constructor like this:
RigidBodyElement(RigidBody body)
{
....
}
And instantiate it like this in an instance method of RigidBody:
new RigidBodyElement(this);
Upvotes: 3