+ 2

how i can define a variable that share between all classes?

6th Nov 2016, 1:38 PM
KiynL
KiynL - avatar
8 Answers
+ 6
You can use a global variable. But remember that's violating encapsulation and is not recommended.
6th Nov 2016, 3:28 PM
Alireza M
Alireza M - avatar
+ 2
As Harish already mentioned :)
7th Nov 2016, 5:19 PM
Bart Genuit
Bart Genuit - avatar
+ 2
While all these might be valid answers to your question, I would advise you to first ask yourself why you need a 'global data bank' in the first place. The reason that it is generally advised not to use global variables, for example, is because they make the data flow of your program harder to follow. If you need the same data to be available at many places in your code, why not make a class contain this data and pass an object of this class to the pieces of code that need the data? A piece of code doesn't need to be a subclass of the class/object containing the data to be able to access this data.
7th Nov 2016, 5:53 PM
Bart Genuit
Bart Genuit - avatar
+ 1
Use inheritance concept and make variable public
7th Nov 2016, 5:17 PM
Harish Sune
Harish Sune - avatar
+ 1
You can make a superclass that contains the variable and make all classes subclasses of this superclass.
7th Nov 2016, 5:19 PM
Bart Genuit
Bart Genuit - avatar
0
its a good idea but i have another idea that is I define a class then name it global for example then define all requirement as static variables and this class works like a data bank.
7th Nov 2016, 5:43 PM
KiynL
KiynL - avatar
0
i working with unity 3d engine and game programing. its necessary to find a shortcut and flexible way to save, load temp and global variables likes game level completed, how many items unlocked, input controller and other. and sometimes need to make temp connection between classes that i don't know i when the class make in game and maybe no need to inheritance base class.
7th Nov 2016, 6:33 PM
KiynL
KiynL - avatar
0
make a class and then define a member as public and inherit it in all the classess
23rd Nov 2016, 7:03 AM
gulshan kumar
gulshan kumar - avatar