处理同一对象类型的多个实例时出现问题
我正在尝试创建多个名为“问题”的相同自定义对象类型的实例。 Question 类具有 getter 函数来返回问题和问题的答案。如果我只创建一个问题对象,则一切正常,但如果我在调用 getter 函数时创建两个具有不同名称和变量的问题对象,则始终返回最近初始化的问题对象的值。
这就是我的意思:
Question q1 = new Question("What is the capital of France", "Paris");
Question q2 = new Question("What is the capital of England", "London");
System.out.println(q1.getQuestion());
System.out.println(q2.getQuestion());
在控制台中,
What is the capital of England
What is the capital of England
我希望显示两个不同的问题。
有人能指出我正确的方向吗?
I am trying to create a number of instances of the same custom object type called Question. The question class has getter functions to return the question and answer for the question. If I create just one question object everything works fine but if I create two with different names and variables when I call the getter function is always returns the value from the Question object most recently initialized.
This is what I mean:
Question q1 = new Question("What is the capital of France", "Paris");
Question q2 = new Question("What is the capital of England", "London");
System.out.println(q1.getQuestion());
System.out.println(q2.getQuestion());
In the console is displays
What is the capital of England
What is the capital of England
I am expecting to to display the two different questions.
Can anyone point me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果没有看到代码,我只能猜测,但问题类似乎有一个静态变量而不是成员变量。
这就是为什么有些人主张始终在变量前面加上
this.question
和this.answer
,这样您就知道您引用的是成员变量,而不是任何其他变量。它会很快指出这样的错误。所以如果你已经
删除了静电,那么它只是
Without seeing the code I can only guess, but it would seem as though the
Question
class has a static variable instead of a member variable.This is why some people advocate always prefacing your variables with
this.question
andthis.answer
so you know you're referring to the member variable, not any others. It would point out a bug like this very quickly.So if you have
remove static so it's just
当您使用 new 运算符时,肯定会创建一个新对象。但是,如果您的类中声明了静态字段,则该字段将在特定类的所有实例之间共享。因此,使用
static
将是导致此行为的原因。When you use
new
operator, a new object is created for sure. But, if there is astatic
field declared in your class, it will be shared across all the instances of the particular class. Hence, the use ofstatic
would be the cause of this behavior.