class - How to bind two classes in java? -


how can bind 2 java classes?

i'm programming 3d opengl program have several different classes. know how bind classes main class, can't bind 2 separate classes together. have class terrain have list containing data terrain. need data in class called figure isn't main class. have tried bind these classes this:

in terrain class have:

figure fig;  public void bindclasses(figure fg) {    fig = fg; } 

and in figure class have:

terrain ter;  public void bindterrain(terrain tr) {    ter = tr; } 

and in both classes call functions. shouldn't bind them , variables? @ least that's how have bound classes main class.

just start off terminology. class blueprint tells how instantiated object - moment write new figure(), you've created instance, an object of class figure (often have several objects of 1 class). when "binding" above, not binding classes, binding objects.

the above code fine. convention, write sort of things setters, it's not necessary call them that, common pattern is:

public class terrain {      figure fig      public void setfigure(figure fig) {        this.fig = fig;     }  }  public class figure {      terrain ter      public void setterrain(terrain ter) {        this.ter = ter;     }  } 

to associate 2 in main class do, which, see, pretty have already, using conventional names.

public void init() {     terrain ter = new terrain();   // create object of class terrain    figure fig = new figure();     // create object of class figure     ter.setfigure(fig);    fig.setterrain(ter);  } 

if there's relationship between 2 objects, instance, can't create figure without having terrain put in. make terrain "own" figure. indicate using constructor on figure.

public class figure {      terrain ter      // constructor requires instance of terrain,      // since figure must placed in terrain     public figure(terrain ter) {         this.ter = ter;         // let terrain know main figure.        ter.setfigure(this);               }  } 

now init code instead look:

public void init() {     terrain ter = new terrain();   // create object of class terrain    figure fig = new figure(ter);  // create object of class figure in terrain     // no setters needed, since figure constructor sets    // relationship.  } 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -