user6091183
user6091183

Reputation: 31

Initialization in an extending class

I am confused with initialization in parent class. I need a brief explanation on how this works.

public class Bullet extends NextUnit {

    public static int numBullets;

    public Bullet() {
        super();
    }

    public Bullet(GameMain gameMain, AnimInfo animInfo, double x,double y, double xOnMap, double yOnMap,
        double degree, double speed, double speedBackward, double speedRotate, int state) {
        super(gameMain, animInfo, x, y, xOnMap, yOnMap, degree, speed, speedBackward, speedRotate, state);
    }

    // other parts of code are omitted 
}

Where would I initialize the numBullets?

Upvotes: 1

Views: 79

Answers (3)

Andrew
Andrew

Reputation: 49606

Where would I initialize the numBullets?

First of all, you should understand that the variable has already initialized by the default value (0 for int). You could use the following ways to initialize your variable:

  1. the static initialization block static { numBullets = 1; }
  2. a static method, e.g. public static int increaseAndGet() { return ++numBullets; }
  3. directly together with declaration public static int numBullets = 1;

The variable numBullets is not an instance member, it is a class variable. The numBullets has no relation to the parent class, it's just a part of Bullet class. You should use static members for interaction with it.

  1. together with instance members for clever goals.

In your case, I suggest writing the next code snippet:

{ updateNumBullets(); }

private static int numBullets;

private static void updateNumBullets() { ++numBullets; }

Upvotes: 1

gevorg
gevorg

Reputation: 5055

First of all you don't need to assign default value to numBullets, by default it is zero. In case you want it to have another value you can do it using inline assignment like this:

public static int numBullets = 43;

or using static block like this:

public static int numBullets;
static {
  numBullets = 44;
}

Upvotes: 0

Alfred Rossi
Alfred Rossi

Reputation: 1986

Did you intend to declare it static? A static variable will be shared by all instances. You can simply set its value inline (if it's a constant) or with a one assignment somewhere else.

If it's not meant to be shared among all instances of "bullet" then drop static and set it to whatever defaults make sense in each constructor (before or after super). If you need additional arguments for that simply add them.

Are you intending to count the number of Bullets that have been instantiated? Then you just do something like initialize it to 0 and increment by one in both constructors.

Upvotes: 1

Related Questions