-2

I have a StepCounter class which extends Counter. Counter has an increment method which adds 1 to the counter. I need override this method so that increment method in the StepCounter class will increment the counter by the value of "step" e.g. if step=2 then the increment would add 2 to the counter instead of 1. Somehow I can't make it work. This is the coding I've done:

public class StepCounter extends Counter {

    //fields
    private int step;

    //constructors
    public StepCounter() {
        super();
        step = 2;
    }

    public StepCounter(int count, int step) {
        super(count);
        this.step = step;
    }

    //methods
    public void setStep(int step) {
        this.step = step;
    }

    public int getStep() {
        return step;
    }

    @Override
    public void increment() {
        super.getCount() += step;
    }   
}

I've already tried various styles like

super.getCount() += getStep();

etc...

BTW getCount() method returns count value from Counter class.

Dominik Sandjaja
  • 6,326
  • 6
  • 52
  • 77
Lazio
  • 105
  • 1
  • 10
  • 1
    What do you want to do with the incremented value? It is never assigned anywhere?! – Dominik Sandjaja Mar 03 '15 at 14:29
  • @DaDaDom, the increment method should increment the count value from the Counter class. I've used super.getCount() because it returns count value. I want to create an ArrayList of type StepCounter and add some data into it. I then want to create a for loop which will print 10 results one next to another showing how the counter works. – Lazio Mar 03 '15 at 14:34

2 Answers2

3

You get the value, but you dont set it.
Try it this way:

setCount(getCount() + step);

Also the super keyword isn't needed in this case, if your inheriting class doesn't override getCount(), it's much more readable without it.

Zhedar
  • 3,480
  • 1
  • 21
  • 44
  • 1
    @Lazio you should really start accepting answers that helped you, so that others see, that those questions are answered. – Zhedar Mar 03 '15 at 15:10
0

the getCount() method is inherited from counter so you should go this way

 @Override
    public void increment() {
        Integer tmp = this.getCount() += step;
        setCount(tmp);
    } 

Also in the no-arguments constructor you should initialize the step variable properly.

public StepCounter() {
    super();
    this.step = 2;
}
Dragan
  • 455
  • 4
  • 12
  • `Also in the no-arguments constructor you should initialize the step variable properly.` There is no need to use `this` here. – Tom Mar 03 '15 at 14:36
  • 1
    As i suspect `count` to be primitve, this summons unnecessay autoboxing. – Zhedar Mar 03 '15 at 14:37
  • I avoid primitives when dealing with mathematical operations anywhere for reasons of my own and prefer autoboxing with exception handling. – Dragan Mar 03 '15 at 14:39
  • http://stackoverflow.com/questions/5199359/why-do-people-still-use-primitive-types-in-java#5199425 – Tom Mar 03 '15 at 14:49