gpt4 book ai didi

java - 在构造函数之外的方法中使用构造函数中的变量

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:34:37 25 4
gpt4 key购买 nike

如果我有这样的构造函数:

    public Constructor (int a, int b){

int c = a;
int d = b;
}

然后我如何在与构造函数相同的类中的方法中使用变量 c 和 d,因为尝试仅在方法中使用变量名称似乎不起作用?

最佳答案

事实上,您的代码无法编译 - int c = int a 无效。

我假设您的意思是:- int c = a;

How can i then use variable c and d in a method within the same class as the constructor

你不能,因为你已经将它们声明为局部变量,其作用域在构造函数结束执行时结束。

您应该将它们声明为实例变量。

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);
}
}

关于java - 在构造函数之外的方法中使用构造函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13500170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com