So I have object
@Data
public class Bicycle{
private String color;
private long speed;
private String tag;
public Bicycle(String color, long speed){
color = color;
speed = speed;
}
public void setTag(String tag){
tag = tag;
}
}
I also have a Helper class that contains all my constants where I store a Bicycle I want to reference alot. I want to add a Bicylce with color="blue",speed=5L,tag="mountain" as a public static variable but I'm not sure how to do that since the constructor doesnt use tag, and setTag returns void. I don't own this Bicycle class so I can't add it to the constructor.
public class Helper{
public static final Bicycle = new Bicycle("blue",5L);
}
Because of this, whenever I have to create this bicycle
main{
Bicycle bicycle = Helper.Bicycle;
Bicycle.setTag"mountain");
}
How would I create this bicycle with the "mountain" tag in the Helper class?
Add a static block in your Helper like:
public class Helper {
public static final Bicycle bicycle = new Bicycle("blue", 5L);
static {
bicycle.setTag("mountain");
}
}
And fix the assignments like tag = tag -> this.tag = tag.
You can add a static block into your helper class to do more stuff you cannot do when you instantiate your object.
public class Helper {
public static final Bicycle bicycle = new Bicycle("Blue", 5L);
static {
bicycle.setTag("mountain");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With