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

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.

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.

Here is my main class:

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); }}

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);}}

class C with timer 2

import java.util.TimerTask;

public class classC extends TimerTask

{

classB b = new classB();

public void run(){

System.out.println(b.getint());}}

How could i fix so i it works using private int counter;?

解决方案

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());

}

}

the code will work.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值