[英]java using getter and setter methods and returning 0
我在2個單獨的類中創建了2個計時器。 一個計時器遞增int計數器。 另一個使用get方法並打印出int計數器的值。
問題是如果我使用private int counter
,第二個計時器只打印出0、0、0等,而如果我要使用private static counter
則它打印出我想要的1,2,3,4,5等。 但是我寧願不使用static
因為我已經被告知它是不好的做法。
這是我的主要課程:
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類
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;
?
您基本上已經創建了兩個左右的實例,在內存中稱為兩個不同的對象。 因此,一個對象的實例如何打印另一個對象的值。 要么使用靜態計數器,要么將引用傳遞給同一對象。
您有兩個完全唯一/分離的ClassB實例,一個實例使用計時器運行,另一個實例顯示。 顯示的一個永遠不會更改,因為它沒有在計時器中運行,因此它將始終顯示初始默認值0。
如果更改它,則只有一個實例:
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標准。 例如,請參閱上面的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.