java - What is the reason why this variabe change from main method is not effected on upper Class -


please forgive if of novice question, need understand why call b.createnumb(1) in main method effect change on numb in classb.

class classb {         int numb = 0;         public int getnumb(){             return numb;         }         void createnumb(int num){             numb = num;         }        }      public class classa {         classb b = new classb();          // returns numb classa             public int returnb(){             return b.getnumb();         }           public static void main(string[]args){                 classa = new classa();              classb b = new classb();         //my espectation b.createnumb(1) should update numb in classa              b.createnumb(1);              system.out.println(a.returnb());          }            } 

the code when run prints 0 instead of 1; please need explanation happening behind code. thanks.

this wouldn't work because creating separate instances of classb. if want work, have pass instance classa. this:

public class classa {     classb b;     public classa(classb b){        this.b = b;     } //... 

then can do classa = new classa(b).

changing 1 value of instance doesn't affect instances. if used static. think research static learn.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -