Whats the best way to reference variables from another class in a project, I know how to do it to objects but not variables.
Thanks
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.
Whats the best way to reference variables from another class in a project, I know how to do it to objects but not variables.
Thanks
Add getter and setter methods to the class containing the variable and use them to get to the variable.
Or you could make the variable public.
Use static variables. They are class variables.You will always get updated values when they are altered between methods of different classes.
Class variables are normally meant to be kept safe for a reason.
When you have an exception to the rule, (only you can prevent bad code) you have options.
Getter methods are lame, but simple and to the point, and they keep most of your protection intact.
If your variable(number) is specific to an Object
public class Creator { private int number; // I am unique to every Creator Object public Creator(){ number = 7; } public int getNumber(){ return number;} //main method public static void main(String[] args){ int giveMeNumber; Creator user = new Creator(); giveMeNumber = user.getNumber(); // returns the number variable } }
If your varaible(number) is used by all Objects in the Class
public class Creator { private static int number = 7; //I exist once for all Creator Object to share me. (Should be initialized almost ALWAYS) public static int getNumber(){ return number;} //NOTICE** the method is now static //main method public static void main(String[] args){ int giveMeNumber; giveMeNumber = Creator.getNumber(); // the Class itself is used to gain permission. //Though, this will still work and is useful in situations. (AKA: nothing wrong with it) Creator user = new Creator(); giveMeNumber = user.getNumber(); // returns the number variable } }
hope this helps!
Jonathan