如果我有这样的构造函数:
public Constructor (int a, int b){ int c = a; int d = b; }那我该如何在构造函数的同一个类中的方法中使用变量c和d,因为试图在方法中只使用变量名似乎不起作用?
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?
最满意答案
实际上你的代码不会编译 - 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); } }In fact your code will not compile - int c = int a is not valid.
I assume that you meant: - int c = a;.
How can i then use variable c and d in a method within the same class as the constructor
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); } }更多推荐
发布评论