here I am trying to call overloaded constructor after some condition has met in my main() program , which is given by variable a. Code works fine when I am using only default constructor , but I need to call overloaded constructor at some point and it fails . folowing is code:
overloaded constructor :
public Paddle(int a){
if(a ==1){
ImageIcon ii = new ImageIcon(this.getClass().getResource(paddle1));
image = ii.getImage();
}
else {
ImageIcon ii = new ImageIcon(this.getClass().getResource(paddle2));
image = ii.getImage();
}
width = image.getWidth(null);
height = image.getHeight(null);
resetState();
}
// further initialization --
default constructor :
public Paddle(){
ImageIcon ii = new ImageIcon(this.getClass().getResource(paddle));
image = ii.getImage();
width = image.getWidth(null);
height = image.getHeight(null);
System.out.println(height+" "+width);
resetState();
}
thanks for help in advance, further queries can be asked but I think this piece of code has some problem . Thank you
Answer
You are not setting the instance variable
imagein the overloaded constructor.Correct Way
The way you are doing it is violating DRY ( Don’t Repeat Yourself )!
The best way is to make the
no argconstructor call the overloaded one and then set the instance variableimagein one place.A better way would be to just pass in the resource to a single constructor and be done with it, without seeing all the code, this looks overly complicated.