gpt4 book ai didi

java - 为什么 Eclipse 建议我将我的方法设为静态

转载 作者:搜寻专家 更新时间:2023-10-31 08:06:03 25 4
gpt4 key购买 nike

我正在从一个类中调用一个方法,它给我一个错误,让我将方法设为静态。当我问这个问题时,我对为什么感到困惑 What's the difference between a class variable and a parameter in a constructor?我的理解是类变量是静态的。

患者类别:

public  String  setOption(String option) throws IOException
{
option = stdin.readLine();
//stuff here
return option;
}

患者管理系统:

public class PatientManagementSystem
{
static BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));
public static void main(String[] args) throws IOException
{
Patient.setOption(null);
}
}

错误:
enter image description here

我是将方法更改为静态方法还是创建局部变量?

最佳答案

根据您之前的问题,我认为可能没有充分挖掘局部变量 的概念。在这个方法中:

public String setOption(String option) throws IOException
{
option = stdin.readLine();
return option;
}

option 是一个局部变量。每次调用 setOption 方法时,您都将该变量的初始值 作为参数传递给它(而您碰巧忽略了该值),但该细节不在顺便说一句,这和

public String setOption() throws Exception
{
String option = stdin.readLine();
return option;
}

现在,局部变量与实例或类变量完全不同:它们仅在方法体内有效,并且仅在方法执行期间存在。考虑到这一点,让我们看一下这段代码:

static BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));
public static void main(String[] args) throws IOException
{
Patient.setOption(null);
}

在这里,您基本上是在滥用类变量 stdin 来处理本应是局部变量的内容:

public static void main(String[] args) throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
Patient.setOption(null);
}

关于您的方法调用的问题...setOption 目前是一个实例 方法,这意味着它必须在实例的上下文中调用。您按原样调用它,不涉及任何 Patient 实例。如果你继续沿着这条路走下去,你将只能代表一个病人,这可能不是你的想法。所以你想保持方法不变并创建一个 Patient 的实例:

Patient p = new Patient();
p.setOption(...);

在你的整体设计中,不清楚setOption应该扮演什么角色,但是它使用静态stdin变量并不是一个好主意(我已经做到了本地以上)。您希望将从 stdin 读取的任何数据传递给 setOption 方法,从而将其与输入读取逻辑分离。

关于java - 为什么 Eclipse 建议我将我的方法设为静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19812989/

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