How can I bind together two Java classes?
I’m programming a 3D opengl program where I have several different classes. I know how to bind classes to the main class, but I can’t bind two separate classes together. I have a class Terrain where I have a list containing some data about the terrain. Then I need that data in another class called Figure which isn’t the main class. I have tried to bind these classes together like this:
In Terrain class I have:
Figure fig;
public void bindClasses(Figure fg) {
fig = fg;
}
And then in the Figure class I have:
Terrain ter;
public void bindTerrain(Terrain tr) {
ter = tr;
}
And then in both classes I call those functions. Shouldn’t that bind them and their variables? At least that’s how I have bound my classes with the main class.
Just to start off with terminology. A class is a blueprint that tells you how an instantiated object is – the moment you write
new Figure(), you’ve created an instance, an object of the classFigure(often you have several objects of one class). So when you are “binding” above, you are not actually binding classes, you are binding objects.The above code is fine. By convention, you often write that sort of things with setters, it’s not necessary to call them that, but a very common pattern is:
To associate the two together you would in your main class do, which, as you see, is pretty much exactly what you would have already, just using the conventional names.
If there’s a relationship between the two objects, for instance, you can’t create a figure without having a terrain to put it in. Which would make terrain almost “own” figure. You could indicate this by using the constructor on figure.
Now your init code would instead look: