Wednesday, 15 July 2015

java - How do I access a class's variables from a class that I created within that class? -



java - How do I access a class's variables from a class that I created within that class? -

i have 2 classes such:

public class a{ arraylist<runnable> classblist = new arraylist<runnable>(); int x = 0; public a(){ //this code here in loop gets called variable number of times classblist.add(new b()); new thread(classblist.get(classblist.size())).start(); } } public class b implements runnable{ public b(){ } public void run(){ //does things here. blah blah blah... x++; } }

the problem need have instance of class b alter variable x in class a, class created class b. however, not know how allow class b know needs alter value or if can. suggestions on how alter appreciated. give thanks you!

you need give b instance access a instance. there couple of ways that:

make b derive a , create info fields (or accessors them) protected in a. tend shy away one.

make b take a instance in constructor.

make b take instance of class implements interface in constructor, , have a implement interface.

which take you. i've given them in decreasing order of coupling, more loosely-coupled, improve (usually).

that 3rd alternative in code:

public theinterface { void changestate(); } public class implements theinterface { arraylist<runnable> classblist = new arraylist<runnable>(); int x = 0; public a(){ //this code here in loop gets called variable number of times classblist.add(new b(this)); // <=== passing in `this` `b` instance has access new thread(classblist.get(classblist.size())).start(); } // implement interface public void changestate() { // ...the state alter here, instance: x++; } } public class b implements runnable{ private theinterface thing; public b(theinterface thething){ thing = thething; } public void run(){ // alter thing's state thing.changestate(); } }

now, both a , b coupled theinterface, a coupled b; b not coupled a.

java class

No comments:

Post a Comment