Passing values between two classes
Hi
It is a basic OOP methodology that the members of a class can be passed into other class by making other class sub class of that class using extends keyword.
My question regarding this is I want to assign a value of a variable say
int i of a class say class A into a variable say int j of another class say class B without any using of inheritance.
Is this possible?
class A
{
int i=6;
}
class B
{
int j;
}
The second problem in it is that I have created a method that the value of int i is changing, so I want to pass it in the int j variable and save it in j. So whenever I want to call the saved value I get it. How this is possible?
Thanks in Advance
Re: Passing values between two classes
use accessor and mutator methods.
an accessor method will retrieve a value, and a mutator method will change the value.
heres a simple class using both of these:
Code:
public class ChangingVars
{
int i;
public ChangingVars(int input)
{
this.i = input;
}
//accessor method
public int getValue()
{
return this.i;
}
//mutator method
public void changeValue(int newVal)
{
this.i = newVal;
}
}
and then in another class where you would have something like:
Code:
public class UsingChangingVars
{
public static void main(String[] args)
{
//stores the integer 10 in the ChangingVars object var1
ChangingVars var1 = new ChangingVars(10);
//stores the integer 17 in the ChangingVars onject var2
ChangingVars var2 = new ChangingVars(17);
//getting a value out of the object
int gettingTheValue = var1.getValue();
//setting the value in the object
var2.changeValue(gettingTheValue);
//or doing both at once
var2.changeValue(var1.getValue());
}
}
Re: Passing values between two classes
Global variables should be private, otherwise there's no need to have accessor and mutator methods because you can access it directly. Make variable i private and you're good to go.
Code:
public class ChangingVars
{
private int i;
Re: Passing values between two classes
bad habbits are hard to get rid of :)
Re: Passing values between two classes
Quote:
Originally Posted by TBeck
bad habbits are hard to get rid of :)
Don't worry, I've been there and done that. :D