3

This might sound like a trivial question but I don't know of an easy way to do it.

How can I construct a class instance in Java with default/sample values? The object may have other objects as part of its construct.

Jayz
  • 1,174
  • 2
  • 19
  • 43
  • I am looking at a solution which uses java reflection to do that for me. My class is big, has embedded objects and creating an unnecessary constructor allows it to be misused by other programmers in the team. – Jayz Feb 08 '13 at 07:29
  • I'm very late to the party, but in case anyone else comes along with a similar question, you might want to look into the [Builder pattern](https://howtodoinjava.com/design-patterns/creational/builder-pattern-in-java/) and [see this question and answer](https://stackoverflow.com/questions/21054070/how-to-use-default-value-in-the-builder-pattern-if-that-value-is-not-passed-and) – Barry Feb 20 '21 at 23:55

3 Answers3

2

Assign default value at time of variable declaration. Example -

public class Model{
  private String model = "default"; // Default value
  public String getModel(){
      return model;
  }
  public void setModel(String model){
      this.model = model;
  }
}

Or assign value through constructor.

public class Model{
  private String model;
  public Model(String model){
      this.model = model;
  }
  public String getModel(){
      return model;
  }
  public void setModel(String model){
      this.model = model;
  }
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

You can give default values in constructor or give it while defining your class.

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
  • Thx for the suggestion but I am looking at a solution which uses java reflection to do that for me. My class is big, has embedded objects and creating an unnecessary constructor allows it to be misused by other programmers in the team – Jayz Feb 08 '13 at 07:28
  • @Jayz: I think using reflection will be more tedious and IMO thats not the appropriate way. – Ajinkya Feb 08 '13 at 08:47
  • 1
    Thats why I am looking for a framework/library which does that, I know how to write the code using reflection but I understand that will be tedious. Json-parsing tools like Jackson probably do it internally and I guess, Easymock does something similar. – Jayz Feb 08 '13 at 08:56
  • @Jayz: Easymock is there for completely different purpose. Looks like you are making it much complex. May be revisit your problem again and think if you really need reflection/Easymock. – Ajinkya Feb 08 '13 at 09:59
0

Have the values assigned in your constructor? As in the following:

public class Foo {
  private int bar;
  public Foo(int barValue) {
   super();
   this.bar = barValue;
  }
  public void setBar(int aBarValue) { this.barValue = aBarValue; }
  public int getBar() { return this.barValue; }
  public String toString() { return new Integer(this.getBarValue()).toString(); }
}
hd1
  • 33,938
  • 5
  • 80
  • 91