我想将我的方法级别变量设置为类级别变量。是否有可能将方法级别变量设置为Java中的类级别变量?我想将方法级别变量值作为类级别变量如何获取?是否可以将方法级别变量设置为类级别变量?
class A {
void m(String s){
String s1 = s;
}
}
我想将我的方法级别变量设置为类级别变量。是否有可能将方法级别变量设置为Java中的类级别变量?我想将方法级别变量值作为类级别变量如何获取?是否可以将方法级别变量设置为类级别变量?
class A {
void m(String s){
String 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
}
}
我猜你想要的(作为一个基本的例子)
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;
}
}
如果您在该方法中询问如何设置实例变量,请按照以下步骤操作。
String s;//instance var
void m(String s)//s is dynamic value
{
this.s=s;
}
它被称为字段或实例变量。 – Bartzilla 2013-02-22 22:25:20
当你编辑你的问题时,不要删除以前的内容,而是**添加**新的信息(否则答案将是无用的未来访客) – 2013-02-22 22:53:17
我不明白新问题,代码看起来像它已经工作。你能解释一下还是提供你想达到的更多细节? – 2013-02-22 22:54:57