Reputation: 79
I have code like this:
public class Class1 {
public void method1() {
...
Class2 c = new Class2(i);
...
}
public Class1(int i) {
...
}
}
How can I get variable i from constructor to method1 ?
Upvotes: 0
Views: 95
Reputation: 24334
You need to declare a field in the class. E.g.
private int i;
Then in the constructor set this.i = i;
You can then access i
from anywhere in the class.
To be honest this is pretty basic stuff so Id suggest reading up on Java basics before continuing a project :)
Upvotes: 2
Reputation: 68962
Use member variable i to store the value
public class Class1 {
private int i;
public void method1 () { ...
Class2 c = new Class2(i);
... }
public Class1 (int i){
this.i = i;
...
}}
Upvotes: 2
Reputation: 14053
You can put i
as an instance variable.
public class Class1 {
private int i;
public void method1 () {
...
Class2 c = new Class2(i);
...
}
public Class1 (int num){
this.i = num;
}
}
Upvotes: 2