Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a object in a static constant helper class with void set methods?

Tags:

java

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?


2 Answers

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.

like image 96
pirho Avatar answered Jan 24 '26 19:01

pirho


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");
   }
}
like image 30
Jeiraon Avatar answered Jan 24 '26 20:01

Jeiraon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!