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.
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.
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;
}
}
You can give default values in constructor or give it while defining your class.
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(); }
}