java使用getter和setter方法并返回0

时间:2015-11-29 03:11:55

标签: java encapsulation setter getter

我在2个不同的课程中创建了2个计时器。一个计时器递增int计数器。另一个使用get方法并打印出int counter的值。

问题是第二个计时器只打印出0,0,0等,如果我使用private int counter 而如果我使用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);}}

C级,带有计时器2

import java.util.TimerTask;
public class classC extends TimerTask 
{
classB b = new classB();

public void run(){
System.out.println(b.getint());}}

我怎么能修复,所以我使用private int counter;

2 个答案:

答案 0 :(得分:2)

你基本上创建了两个单独的实例,在内存中称为两个不同的对象。那么,一个对象的实例如何打印另一个对象的值。使用静态计数器或将引用传递给同一对象。

答案 1 :(得分:1)

您有两个完全独特/独立的ClassB实例,一个是您使用Timer运行的,另一个是您显示的。显示的一个永远不会改变,因为它不在Timer中运行,因此它将始终显示初始默认值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标准。例如,请参阅上面的代码。

相关问题