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
Printable View
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
Code :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
Code :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