java 在构造函数之外的方法中使用构造函数中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13500170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using a variable in constructor in a method outside of constructor
提问by Drixy01
if i have a constructor like so:
如果我有一个像这样的构造函数:
public Constructor (int a, int b){
int c = a;
int d = b;
}
How can i then use variable c and d in a method within the same class as the constructor because trying to use just the variables name in the method doesn't seem to work?
然后我如何在与构造函数相同的类中的方法中使用变量 c 和 d,因为尝试在方法中仅使用变量名称似乎不起作用?
回答by Rohit Jain
In fact your code will not compile - int c = int a
is not valid.
事实上,您的代码将无法编译 -int c = int a
无效。
I assume that you meant: - int c = a;
.
我假设你的意思是: - int c = a;
。
How can i then use variable c and d in a method within the same class as the constructor
然后我如何在与构造函数相同的类中的方法中使用变量 c 和 d
You can't because you have declared them as local variables whose scope ends when the constructor ends execution.
你不能,因为你已经将它们声明为局部变量,其作用域在构造函数结束执行时结束。
You should declare them as instance variables.
您应该将它们声明为实例变量。
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);
}
}
回答by y.ahmad
You need to declare the variables as class members, outside the constructor. In other words, declare c and d outside of the constructor like so:
您需要在构造函数之外将变量声明为类成员。换句话说,像这样在构造函数之外声明 c 和 d:
int c;
int d;
public Constructor (int a, int b) {
c = a;
d = b;
}