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 trialHimanshu Shukla
872 PointsCan we intialize a field member already to some value and then add a constructor to the class also?
Can we intialize a field member already to some value and then add a constructor to the class also?
i mean that when we didn't have the constructor PezDespenser() we had the field member intialized to "Yoda". Can we intialize the member characterName to some value and then also ask the user to prompt it in the constructor. And in this case will the constructor work even if we don't pass a string as an argument?
1 Answer
Steve Hunter
57,712 PointsHi there,
In short, yes.
You can have default values set within the class and then have the constructor change that value.
If you want the option of either changing the value, or not, you would need two constructors. One would do nothing; and the second would set the value. A loose example:
public class Demo{
private String nameOfDemo = "A demonstration";
public Demo(){
// do nothing
}
public Demo(String name){
nameOfDemo = name;
}
}
Here, the 'default' constructor takes no parameters and simply does nothing. This is the same as the default constructor that operates when no constructor is defined. As soon as you define one constructor, though, you need to write the default behaviour. In this case, that's no behaviour at all! Then we have the second constructor that overrides the default value of the member variable for the class.
We can apply the same thinking process to the PezDispenser
example:
class PezDispenser {
private String characterName = "Yoda";
public String getCharacterName() {
return characterName;
}
public PezDispenser(String name){
characterName = name;
}
public PezDispenser(){
// do nothing
}
}
public class Example {
public static void main(String[] args) {
// Your amazing code goes here...
System.out.println("We are making a new PEZ Dispenser");
PezDispenser dispenser = new PezDispenser();
PezDispenser dispenser2 = new PezDispenser("R2D2");
System.out.printf("The dispenser is %s %n",
dispenser.getCharacterName()
);
System.out.printf("The dispenser is %s %n",
dispenser2.getCharacterName()
);
}
I hope that helps.
Steve.
Himanshu Shukla
872 PointsHimanshu Shukla
872 Pointsthanx mate appreciate your help