Reputation: 137
I want to set my method level variable as class level variable. Is it possible to set method level variable as class level variable in Java?i want to get method level variable value as class level variable how to get it?
class A {
void m(String s){
String s1 = s;
}
}
Upvotes: 1
Views: 909
Reputation: 304
Try this code
class A {
String s;
void m(String s){
this.s=s; //this keyword is used to ambiguity between local variable and class level variable
}
}
Upvotes: 1
Reputation: 85789
I guess that you want (as a basic example)
class A {
String s1;
void m(String s) {
s1=s;
}
}
Note that this is what you do with a setter function:
public class A {
private String s1;
//Since the attribute is private, you need a function to access to the value
public String getS1() {
return this.s1;
}
public void setS1(String s) {
this.s1 = s;
}
}
And you can also pass the dynamic value in the class constructor:
public class A {
private String s1;
public A(String s1) {
this.s1 = s1;
}
//Since the attribute is private, you need a function to access to the value
public String getS1() {
return this.s1;
}
public void setS1(String s) {
this.s1 = s;
}
}
Upvotes: 3
Reputation: 46428
If you asking about setting the Instance variable in that method here's how you do it.
String s;//instance var
void m(String s)//s is dynamic value
{
this.s=s;
}
Upvotes: 1