Im having trouble with some Java, How do I give in default parameter values in java?.
for example I have this in c++
DVD(int i, string t, int y, string d="Unknown"): Items(i,t,y),director(d){}
and in Java I tried
public Dvd(int i, String t,int y, String d="Unknown"){
super(i,t,y);
director = d;
}
which fails to build. So how do I go about giving in default values?
also In my main testing class I tried giving in 3 arguments insead of 4 but this fails also. How do I get around this problem?.
Java does not support default argument construct like that, unfortunately. The traditional way to implement it, for better or worse, is to use what is called “telescoping” methods.
Here’s a quote from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters:
The telescoping constructor pattern is essentially something like this:
And now you can do any of the following:
You can’t, however, currently set only the
nameandisAdjustable, and leavinglevelsat default. You can provide more constructor overloads, but obviously the number would explode as the number of parameters grow, and you may even have multiplebooleanandintarguments, which would really make a mess out of things.As you can see, this isn’t a pleasant pattern to write, and even less pleasant to use (What does “true” mean here? What’s 13?).
Bloch recommends using a builder pattern, which would allow you to write something like this instead:
Note that now the parameters are named, and you can set them in any order you want, and you can skip the ones that you want to keep at default values. This is certainly much better than telescoping constructors, especially when there’s a huge number of parameters that belong to many of the same types.
So Java does not have default argument mechanism, but the builder pattern is a much better idiom anyway.
See also
Related questions