Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: How to share variable values amongst different classes?

  1. #1
    Junior Member
    Join Date
    Jun 2009
    Posts
    18
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default How to share variable values amongst different classes?

    Hi,
    I've been programming with Java for a while and am still unsure about something pretty fundamental. I am using a GUI to call methods from different classes, which works fine. However, I'm having trouble sharing the variable values from one class to another. Here is an example which I hope makes things clearer.
    I have two public classes Mouse and Cat, with methods executed from a separate class for the GUI. To execute methods from the two classes I creates object in the GUI:

    public Mouse eek = new Mouse();
    public Cat meow = new Cat();
    And then run use these to run methods. Example Mouse method = run() and Cat method = chase():

    eek.run();
    meow.chase();
    However, the problem is I have public variables in these classes that I want to share between them. My question is: What is the best way to do this? I know

    int numCheese = eek.cheese;

    would get the value of cheese from Mouse and assign it to numCheese in the GUI class, but is this the best way or should I encapsulate with getter and setter methods? I want to be able to access Mouse variable values in Cat and visa-versa without having to make explicit copies in the GUI class if possible. It seems like I am going to have a lot of duplicate code in my GUI if I have to keep on copying all these variables in this way for each potential user input - there has to be a more efficient way to share variable information, right?

    Hope all this makes sense, sorry for the annoying examples. Would really appreciate some advise before I start bloating my GUI code


  2. #2
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Smile Re: How to share variable values amongst different classes?

    hi ignite i hope i wont explode... hekhek joke

    anyway about your problem.. it seems very hard to understand not becuase its annoying like you have said
    but im not yet good in java programming,thats why, but since im getting related to what you are trying to know
    ill give some of my knowledge about that,
    im currently studying about defining your own classes in java and luckily that part is what am i studying right now

    about sharing of variables in different classes... maybe you should declare all the variables as public first
    so any objects or classes that will invoke those variables can be accesed. I defined a method and i declared public one of its variables .. and thats when I noticed that i can accessed it ..
    even if i called that variable in another predefined classes that i make., in a proper way.

    If you want to make all your objects accessable ofcourse you should declare it as public.
    and declare it also as static so it can be accessed or called also by a "CLASS NAME" .

    If those variables are from a primitive type or data type avoid using "VOID" type of return

    examples: String,int.long,double.. etc...

    i hop this will help you a little bit. BOOM!

  3. #3
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to share variable values amongst different classes?

    Well this depends, how tight coupled do you want the class cat and mouse to be? In theory they should be as loosely coupled as possible meaning the class cat should only do its own stuff and the class mouse should do its own stuff, why would such different things need to share variables?

    Second, you should most definitely use getter and setter methods, public variables is the worst way of exposing your variables data.

    If you give me a layout of what you have in mind I might be able to help you out by creating a couple of samples.

    // Json

  4. The Following User Says Thank You to Json For This Useful Post:

    igniteflow (August 19th, 2009)

  5. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: How to share variable values amongst different classes?

    It's almost always a bad idea to have public instance variables. You should encapsulate with getters/setters/other methods.

    Because of the way Java handles object variables by reference, you can pass the reference to the cat variable to the mouse and vise-versa, and that way have access to the other object. Ex:

    // main gui
    public static void main(String[] args)
    {
    // set up your GUI
    // create mouse and cat
    Mouse eek = new Mouse();
    Cat meow = new Cat();
    eek.runFrom(meow);
    meow.chase(eek);
    }

    Because Java only passes the references of the cat/mouse, you only have 1 instance of each. Any changes made will be reflected when any reference pointing to that object asks for the information. There are a few sticky points because it seems like this program is multi-threaded (can't have the mouse run, then stop, then the cat chase, then stop, then the mouse run, then stop, etc.), but that's more or less an easy solution.

    For this, it might be a good idea to not have public setters since then the cat/mouse can muck around with each other (almost always bad). Ex: Say you had public setters for the mouse's position. The cat could then set the mouse to be right in front of it and eat it If you declare a method public, it is pretty much impossible to choose who gets to call it. Sometimes protected is not a good idea, either because of inheritance.
    Last edited by helloworld922; August 19th, 2009 at 12:56 AM.

  6. The Following User Says Thank You to helloworld922 For This Useful Post:

    igniteflow (August 19th, 2009)

  7. #5
    Junior Member
    Join Date
    Jun 2009
    Posts
    18
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: How to share variable values amongst different classes?

    Thank you for the replies. I think perhaps I've been structuring my code wrong then, even though it does work. I've been creating lots of public instance variables at the beginning of my classes and accessing them directly, rather than passing them from object to to object. I am correct in thinking it's better to pass variables as below:

    public int takeCheese(int cheese) {
    cheese--;
    return cheese;
    }
    rather than

    public int cheese;
     
    public void takeCheese {
    cheese--;
    }
    Sorry, I'm not going off topic, I'm just thinking if I get all my methods to pass variables in the first example then it would reduce the need for getters and setters. Am I way off?
    Last edited by igniteflow; August 19th, 2009 at 04:16 AM.

  8. #6
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to share variable values amongst different classes?

    Not really actually, your method there makes no real sense as all it does it deduct one from the original variable and then return it, you have effectively created a wrapper method for --variable.

    You might want to still have a cheese variable on your class.

    public class Rat {
     
        private int cheeseLeft;
     
        public int takeCheeseFromThePoorRat() {
            return --cheeseLeft;
        }
     
        public void giveCheeseToTheRat(final int cheese) {
            cheeseLeft += cheese;
        }
    }

    // Json

  9. The Following User Says Thank You to Json For This Useful Post:

    igniteflow (August 20th, 2009)

  10. #7
    Junior Member
    Join Date
    Jun 2009
    Posts
    18
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: How to share variable values amongst different classes?

    Thanks Json, point taken. I'm completing my first large project and although the program works fine, I have pretty much all the code in just a couple of classes with all variables and methods set as public. I've been running through a lot of tutorials and am managing to separate the methods into smaller, more logical classes and protect the variables a bit more. I know from a design point of view this should have been done from the start, but at least I'll know for next time!

  11. #8
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to share variable values amongst different classes?

    You should always learn from what you are doing I believe, its the way forward

    // Json

  12. The Following User Says Thank You to Json For This Useful Post:

    igniteflow (August 20th, 2009)

  13. #9
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: How to share variable values amongst different classes?

    hehe, I remember first getting into OOP. I had no idea why anyone would want to create private variables/methods! Why restrict yourself? Then I started college and it all changed

  14. The Following User Says Thank You to helloworld922 For This Useful Post:

    igniteflow (August 20th, 2009)

Similar Threads

  1. Replies: 1
    Last Post: December 22nd, 2011, 09:55 AM
  2. Reading IEEE float values from files.
    By username9000 in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: June 30th, 2009, 12:56 PM
  3. [SOLVED] Java program using two classes
    By AZBOY2000 in forum Object Oriented Programming
    Replies: 7
    Last Post: April 21st, 2009, 06:55 AM
  4. Java program to find the minimum and maximum values of input data
    By awake77 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: December 20th, 2008, 05:12 PM