Dri*_*y01 3 java methods constructor
如果我有这样的构造函数:
public Constructor (int a, int b){
int c = a;
int d = b;
}
Run Code Online (Sandbox Code Playgroud)
然后我如何在与构造函数相同的类中的方法中使用变量c和d,因为尝试仅使用方法中的变量名称似乎不起作用?
Roh*_*ain 11
实际上你的代码不会编译 - int c = int a无效.
我认为你的意思是: - int c = a;.
然后,我如何在与构造函数相同的类中的方法中使用变量c和d
你不能因为你已经将它们声明为局部变量,其范围在构造函数结束执行时结束.
您应该将它们声明为实例变量.
public class MyClass {
int c;
int d;
public MyClass(int a, int b){
this.c = a;
this.d = b;
}
public void print() {
System.out.println(c + " : " + d);
}
}
Run Code Online (Sandbox Code Playgroud)