java使用getter和setter方法并返回0 [英] java using getter and setter methods and returning 0
问题描述
我在2个单独的类中创建了2个计时器。一个计时器递增int计数器。另一个使用get方法并打印出int计数器的值。
I have created 2 timers in 2 separate classes. One timer increments int counter. and the other uses a get method and prints out the value of int counter.
问题是如果我使用 private int counter
$,第二个计时器仅打印出0、0、0等。 b $ b而如果我要使用私有静态计数器
,它会打印出1,2,3,4,5等,这正是我想要的。但是我宁愿不使用 static
,因为我被告知香港专业教育学院的不良做法。
The problem is the second timer only prints out 0, 0, 0 etc if i use private int counter
whereas if i were to use private static counter
it prints out 1,2,3,4,5 etc which is what i want. But i would rather not use static
because ive been told its bad practice.
这是我的主要课程:
import java.util.Timer;
public class Gettest {
public static void main(String[] args) {
classB b = new classB();
classC c = new classC();
timer = new Timer();
timer.schedule(b, 0, 2000);
Timer timer2 = new Timer();
timer2.schedule(c, 0, 2000); }}
具有timer1的B类
class B with timer1
import java.util.TimerTask;
public class classB extends TimerTask {
private int counter = 0;
public int getint()
{ return counter;}
public void setint(int Counter)
{ this.counter = Counter;}
public void run()
{ counter++;
this.setint(counter);}}
带有计时器2的C类
import java.util.TimerTask;
public class classC extends TimerTask
{
classB b = new classB();
public void run(){
System.out.println(b.getint());}}
我该如何解决,以便它可以使用 private int counter;
吗?
How could i fix so i it works using private int counter;
?
推荐答案
您有两个完全唯一/独立的ClassB实例,一个实例使用Timer运行,另一个实例显示。显示的一个永远不会更改,因为它没有在计时器中运行,因此它将始终显示初始默认值0。
You've got two completely unique/separate ClassB instances, one you run with a Timer, the other you display. The displayed one never changes since it's not run in a Timer, and so it will always display the initial default value of 0.
如果更改它,则只有一个实例:
If you change it so you have only one instance:
import java.util.Timer;
import java.util.TimerTask;
public class Gettest {
private static Timer timer;
public static void main(String[] args) {
ClassB b = new ClassB();
ClassC c = new ClassC(b); // pass the B instance "b" into C
timer = new Timer();
timer.schedule(b, 0, 2000);
Timer timer2 = new Timer();
timer2.schedule(c, 0, 2000);
}
}
class ClassB extends TimerTask {
private int counter = 0;
public int getint() {
return counter;
}
public void setint(int Counter) {
this.counter = Counter;
}
public void run() {
counter++;
this.setint(counter);
}
}
class ClassC extends TimerTask {
ClassB b;
// add a constructor to allow passage of B into our class
public ClassC(ClassB b) {
this.b = b; // set our field
}
public void run() {
System.out.println(b.getint());
}
}
代码将起作用。
作为辅助建议,请再次进行代码格式化,并努力使其符合Java标准。例如,请参见上面的代码。
As a side recommendation, again, please work on your code formatting, and strive so that it conforms to Java standards. For example, please see my code above.
这篇关于java使用getter和setter方法并返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!