Reputation: 31
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
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:
static { numBullets = 1; }
public static int increaseAndGet() { return ++numBullets; }
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.
In your case, I suggest writing the next code snippet:
{ updateNumBullets(); }
private static int numBullets;
private static void updateNumBullets() { ++numBullets; }
Upvotes: 1
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
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 Bullet
s that have been instantiated? Then you just do something like initialize it to 0 and increment by one in both constructors.
Upvotes: 1