Reputation: 43
Based on the title, how do I set a value passed from a method and set it so that I can access it globally?
For example
A.java
// A.java
public class A
{
new B(2);
}
In B.java
// B.java
public class B
{
B(int num)
{
// Stuffs to do
}
}
From the example, I pass the value(2) from A.java to B.java. But in B.java, how do I make the value globally so that I can access in every methods.
Upvotes: 1
Views: 45
Reputation: 8357
public class B
{
private int number;
public int getNumber()
{
return number;
}
public B(int num)
{
this.number = num;
}
}
Once B(int num) is called, you can access number value via it's getter method like this.
B bObj = new B(10);
bObj.getNumber(); // will return value of 10
Upvotes: 0
Reputation: 68715
If you want to access the value of a variable using the same instance of class B then add an instance member variable. If you want the value to be set and shared by all the instances then add a public static variable in B.java and set its value using constructor input.
Upvotes: 0
Reputation: 647
public class B
{
int classWideInt;
B(int num)
{
classWideInt = num;
// Stuffs to do
}
}
Upvotes: 1