Java Java Objects Meet Objects Constructors

Can 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
MOD
Steve Hunter
Treehouse Moderator 55,710 Points

Hi 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:

PezDispenser.java
class PezDispenser {
  private String characterName = "Yoda";

  public String getCharacterName() {
    return characterName;
  }

  public PezDispenser(String name){
    characterName = name;
  }

  public PezDispenser(){
    // do nothing
  }
}
Example.java
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.

thanx mate appreciate your help