Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Sharad Shivmath
14,446 PointsNamed parameters in constructor
Hi,
When writing this line: mCurrentAttempt = new Attempt(kind, "");
I came across an issue: I had defined the constructor for Attempt as: public Attempt(String mMessage, AttemptKind mKind) { this.mMessage = mMessage; this.mKind = mKind; mRemainingSeconds = mKind.getmTotalSeconds(); }
So, I got an error, when I wrote mCurrentAttempt = new Attempt(kind, ""); The correct way is: mCurrentAttempt = new Attempt("", kind);
Is there a way in Java to specify named parameters to avoid confusion?
I think in C#, it is: function(param1: val1, param2: val2);
Thanks
1 Answer
Bruno Areias
5,181 PointsHI, to my knowledge java does not allow you to do that...
But you can archieve what you are asking for by using the constructor's signature to do it...
class Attempt{
public Attempt(String mMessage, AttemptKind mKind){
//DO STUFF
}
public Attempt(AttemptKind mKind, String mMessage){
//DO STUFF
}
}
They are considered other ways to construct your class and as so they will be valid to do permutations of the constructor variables. As a note, if you want to archive full permutation of variables you should use a Builder design pattern to archieve it.