Search code examples
javaencapsulationsettergetter

java using getter and setter methods and returning 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;?


Solution

  • 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.