我想将方法级变量设置为类级变量。是否可以在Java中将方法级别变量设置为类级别变量?我想获取方法级别变量值作为类级别变量如何获取它?
class A {
void m(String s){
String s1 = s;
}
}
答案 0 :(得分:3)
我想你想要(作为一个基本的例子)
class A {
String s1;
void m(String s) {
s1=s;
}
}
请注意,这是您使用setter函数执行的操作:
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;
}
}
您还可以在类构造函数中传递 dynamic 值:
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;
}
}
答案 1 :(得分:1)
如果您在此方法中询问如何设置实例变量,请按照以下方式进行操作。
String s;//instance var
void m(String s)//s is dynamic value
{
this.s=s;
}
答案 2 :(得分:1)
试试此代码
class A {
String s;
void m(String s){
this.s=s; //this keyword is used to ambiguity between local variable and class level variable
}
}