What is the proper way to get variables to be seen by both classes? Where do you declare them? Do you declare them outside of the classes or do you refer to them in a special way?
Sharing variables between classes
Page 1 of 15 Replies - 22742 Views - Last Post: 22 June 2008 - 12:15 AM
Replies To: Sharing variables between classes
#2
Re: Sharing variables between classes
Posted 21 June 2008 - 04:38 AM
nombre, on 20 Jun, 2008 - 10:52 PM, said:
What is the proper way to get variables to be seen by both classes? Where do you declare them? Do you declare them outside of the classes or do you refer to them in a special way?
you cant declare a variable outside a class. The best method is to initialize a new instance of a class within the other class to call the first classes variables.
EX:
classone has 3 variables:
public class classone
{
int variableone = 25;
String variabletwo = "Your age";
int variablethree = 18;
}
now we want to call these three variables from classtwo so we would do this:
public class classtwo
{
classone classone = new classone();
int newvariable = classone.variableone;
//rest of code
}
#3
Re: Sharing variables between classes
Posted 21 June 2008 - 02:18 PM
rgfirefly24 does your example give the variable newvariable the value of classone.variableone at the end of the class or the beginning?
#4
Re: Sharing variables between classes
Posted 21 June 2008 - 04:19 PM
the way its shown it does it at the beginning, but you can do it anywhere throughout the code of classtwo.
#5
Re: Sharing variables between classes
Posted 21 June 2008 - 07:25 PM
nombre, on 21 Jun, 2008 - 02:18 PM, said:
rgfirefly24 does your example give the variable newvariable the value of classone.variableone at the end of the class or the beginning?
Firstly it wouldn't assign the variable at all not without the Main method
Keep it in a constructor and create a second object or just write the whole code in the Main method sparing you the pain of creating another object ... And the order of allotment is the order of steps ...
As soon as you create an object of First class the first class variable is initialised i.e something physical is created(in memory) and then the next step assigns the new variable in second class to the value of first variable
#6
Re: Sharing variables between classes
Posted 22 June 2008 - 12:15 AM
Never mind. Sorry about taking up boxes.
This post has been edited by nombre: 22 June 2008 - 12:59 AM
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote






|