I need to create a method with a default constructor, which sets name to an empty string and sets both credits and contactHours to zero. How to do it? Thanks, Pieter.
-
2Methods don't have constructors. However, assuming you mean a class, then by reading the documentation. This is surely an assignmentThe Archetypal Paul– The Archetypal Paul2010-12-06 13:23:32 +00:00Commented Dec 6, 2010 at 13:23
-
1Damn... Such a default constructor smells mutability :(SyntaxT3rr0r– SyntaxT3rr0r2010-12-06 13:24:51 +00:00Commented Dec 6, 2010 at 13:24
Add a comment
|
5 Answers
Methods don't have constructors... classes do. For example:
public class Dummy
{
private int credits;
private int contactHours;
private String name;
public Dummy()
{
name = "";
credits = 0;
contactHours = 0;
}
// More stuff here, e.g. property accessors
}
You don't really have to set credits or contactHours, as the int type defaults to 0 for fields anyway.
You're likely to want at least one constructor which takes initial values - in which case your parameterless one can delegate to that:
public class Dummy
{
private String name;
private int credits;
private int contactHours;
public Dummy()
{
this("", 0, 0);
}
public Dummy(String name, int credits, int contactHours)
{
this.name = name;
this.credits = credits;
this.contactHours = contactHours;
}
// More stuff here, e.g. property accessors
}
3 Comments
Adriaan Koster
And can't we make the fields final, now that you've provided guaranteed initialization through the constructors?
Jon Skeet
@Adriaan: Potentially... but then the object constructed with the default constructor is pretty useless. It's hard to say without more information, basically.
Adriaan Koster
You are right of course (-: Just thought making fields final a relevant consideration in this context.
public class Bibabu{
private String name;
private int credits;
private int contactHours;
public Bibabu(){
name = ""; // you could also write this.name and so on...
credits = 0;
contactHours= 0;
}
// more code here
}
2 Comments
Pieter
Thank you, I'M teaching myself Java and had all the other more difficult parts done without problem but this method caused me some problems. thanks again for the quick response. Pieter.
Karl Knechtel
"Bibabu" is a new "default name" to me :)
You don't need a constructor:
public class Dummy
{
private int credits = 0;
private int contactHours=0;
private String name="";
/*
public Dummy()
{
name = "";
credits = 0;
contactHours = 0;
}
*/
// More stuff here, e.g. property accessors
}
3 Comments
Jon Skeet
I would only default the value of
name if no other constructors were going to set it - and I'd expect there to be other constructors which do take values. (See my edited answer for an example.)Stan Kurilin
Even more.. You don't need to initialize integers.
Christian Kuetbach
Thats only true, if initialized with 0 :-). I think, its easier to read, if the attibute is initialized with 0.