为和创建字段,并使用参数对其进行初始化。a
b
f()
例如,像这样:
public class CC{
private int a;
private int b;
private int d;
private int c;
public int f(int a,int b)
{
d=a;
c=b;
this.a = a;
this.b = b;
return a+b;
} //want to use a & b outside
public int q(int a, int b)
{
return a+b; //re-initial-is- will delete the previous parameter value;
}
public int w(){
int p=a+b; //error:cannot access or resolve a & b into variables
return p;
}
public int e(){
int u=d+c; //works but this is not the solution
return u;
}
public static void main(String args[]){
CC obj=new CC();
System.out.println(obj.f(3,4));
System.out.println(obj.q(8,9));
System.out.println(obj.w());
System.out.println(obj.e());
}
}
这会将以下内容打印到控制台:
7
17
7
7
但是,字段的使用应取决于您要执行的操作。
例如,如果您想使用a和b一次(用于计算a + b),然后用新值重置它们,并且能够同时使用旧值和新值,则需要执行以下操作:
package test;
public class CC {
private int a;
private int b;
private int d;
private int c;
public int f(int initialA, int initialB) {
this.a = initialA;
this.b = initialB;
return a+b;
} //want to use a & b outside
public int q(int resetA, int resetB) {
// Move values for a + b to other variables for re-use
this.c = a;
this.d = b;
this.a = resetA;
this.b = resetB;
return a+b; //re-initial-is- will delete the previous parameter value;
}
public int w() {
// Use the initial values
int p = c + d;
return p;
}
public int e() {
// Use the reset values
int u = a + b; //works but this is not the solution
return u;
}
public static void main(String args[]){
CC obj = new CC();
System.out.println(obj.f(3,4));
System.out.println(obj.q(8,9));
System.out.println(obj.w());
System.out.println(obj.e());
}
}
这会将以下内容打印到控制台:
7
17
7
17