我想将我的方法级别变量设置为类级别变量。是否可以在 Java 中将方法级别变量设置为类级别变量?我想将方法级别变量值作为类级别变量如何获取?
class A {
void m(String s){
String s1 = s;
}
}
我猜你想要(作为一个基本的例子)
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;
}
}
您还可以在类构造函数中传递动态值:
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;
}
}
试试这个代码
class A {
String s;
void m(String s){
this.s=s; //this keyword is used to ambiguity between local variable and class level variable
}
}
如果您询问如何在该方法中设置Instance 变量,请按以下步骤操作。
String s;//instance var
void m(String s)//s is dynamic value
{
this.s=s;
}