0

I would like to know why do we need to use constructors in examples like this:http://math.hws.edu/eck/cs124/javanotes5/c5/s2.html. I think even if there are no constructors the programs mentioned in the link might run.The code is:

    public class PairOfDice
    {
    public int die1;   // Number showing on the first die.
    public int die2;   // Number showing on the second die.
    public PairOfDice() {
            // Constructor.  Rolls the dice, so that they initially
            // show some random values.
        roll();  // Call the roll() method to roll the dice.
    }

    public PairOfDice(int val1, int val2) {
            // Constructor.  Creates a pair of dice that
            // are initially showing the values val1 and val2.
        die1 = val1;  // Assign specified values 
        die2 = val2;  //            to the instance variables.
    }

    public void roll() {
            // Roll the dice by setting each of the dice to be
            // a random number between 1 and 6.
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }

} // end class PairOfDice

Is constructors used to improve the readability of the program?Could anyone help me.

  • The page you link has several code examples. Please tell which one, specifically you think would run the same without a constructor. If possible, paste the code in your question. Otherwise the question is too vague. – Tulains Córdova Dec 1 '14 at 12:40
  • @user61852:I've updated the post. – justin Dec 1 '14 at 12:47
  • I would guess that readability and reusability are the main reasons for making a class out of it. – Simon Dec 1 '14 at 12:52
  • 1
    I like constructors as they express the mandatory dependencies of an object very well! – Falcon Dec 1 '14 at 15:27
4

Constructors are not used for readability. In fact, I cannot think an example in which a constructor could be user for readability.

The constructor in the example just gives an initial value to class members.

The class has two constructors:

  • One constructor doesn't receive any parameters. This constructors randomly generates a value for each member by calling the roll() method.
  • The other constructor allows you to set the initial value of the class members.

You are right when you say the class could work without constructors, making it clear that an empty constructor is implied (inherited from Object), so in reality the class will have at least one an empty constructor.

But... as the following no-constructor alternatives show, one could soon reach to the conclusion that providing constructors makes the class more usable:

Constructor-less example 1.

Here, to ensure members have a valid state(*), they where initialized on declaration with a value of one:

public class PairOfDice {
       public int die1 = 1;
       public int die2 = 1;    
       public void roll() {
          die1 = (int)(Math.random()*6) + 1;
          die2 = (int)(Math.random()*6) + 1;
       }    
} 

Constructor-less example 2.

Here, in addition to what was done above, setters were provided to change the value of members arbitrarilly, but then it would be possible to change the values after roll, which is not desirable.

public class PairOfDice {
    public int die1=1;
    public int die2=1;    
    public void setDieOneValue(int i){die1=i;};
    public void setDieTwoValue(int i){die2=i;};
    public void roll() {
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }    
} 

Constructor-less example 3.

Here members values are randomly generated on initialization. Notice repeated code.

public class PairOfDice {
    public int die1=(int)(Math.random()*6) + 1;
    public int die2=(int)(Math.random()*6) + 1;    
    public void roll() {
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }    
} 

(*) by valid state I mean that the members have values that enforce the business rules, or runtime errors. For example, die values should be in the range 1..6 so one should garantee that they don't have zero value at initialization. A business rule is a rule imposed by the "business". The "bunisess" or dice rolling says that die have faces from one to six (I know theere are ther kind of dices but for the sake of simplicity we will leave them out). Having a dice throw a value of 0 would probably make the program fail. That's what is meant by valid state.

  • :Thanks for your answer.I couldn't get what you meant by:"values that enforce the buisness rules or runtime errors".Could you elaborate it. – justin Dec 1 '14 at 14:09
  • @justin I added further explanation at the end. – Tulains Córdova Dec 1 '14 at 14:14
  • Note that in counter example 2, there is the possibility of changing the pair of dice after a roll. This may not be a desirable feature of the class. The original design of the class describes one where the dice value are only setable as part of the initial construction. – user40980 Dec 1 '14 at 14:17
  • @MichaelT you are right. I'll add additional comment in the example stating that. – Tulains Córdova Dec 1 '14 at 14:20
  • (that said, the original class features public mutable members... which is something I rarely see as correct.) – user40980 Dec 1 '14 at 14:21
0

The purpose of a constructor is to initialise the class's members to a known good state. This class has two members - die1 and die2.

The class gas been given two constructors, one of which initialises the members to random numbers, the other initialises them to the values provided.

It's not really about readability. It's to ensure that every instance of that class is always in a valid state from the moment it's constructed.

  • :Could you explain what do you meant by an "valid state". – justin Dec 1 '14 at 13:14
  • 1
    @justin: Valid state means that the members of the class all have an allowed value. In the example with the dice, the allowed values for die1 and die2 are between 1 and 6. The constructor is meant to ensure that die1 and die2 have a value in that range. – Bart van Ingen Schenau Dec 1 '14 at 13:29
  • @BartvanIngenSchenau: Is this only for specifying a state.I think still we can use die1 snd die2 even if we don't use an constructor.Could you help me. – justin Dec 1 '14 at 13:45
  • 1
    The "valid state" refers to the "invariants" of a class - things that are always true. The class is (I assume) intended to model two 6-sided dice. A real die can only show the numbers 1 to 6. So we can create invariants for die1 and die2 saying that both must always lie in the range 1 to 6. If you were to create a version of the class that had no constructors, then die1 and die2 would both default to 0. This is not a correct model of two dice. The class will still "work" in the sense that it can be constructed using the default rules, but it won't be a valid model of two dice. – Simon B Dec 1 '14 at 14:05
  • @justin could you describe how you would set die1 and die2 to valid states (a random number between 1 and 6) without the use of a constructor when no initial values are provided? – user40980 Dec 1 '14 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.